Alternatively, you can use XPath query via XPathSelectElements
method:
var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");
$$
is an alias in Bash to the current script PID. See differences between $$
and $BASHPID
here, and right above that the additional variable $BASH_SUBSHELL
which contains the nesting level.Only suggestion is to access your resp_dict
via .get()
for a more graceful approach that will degrade well if the data isn't as expected.
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
Javascript strings have a length
property that will tell you the length of the string.
Then all you have to do is use the substr()
function to get the last character:
var myString = "Test3";
var lastChar = myString.substr(myString.length -1);
edit: yes, or use the array notation as the other posts before me have done.
Radio inputs must be inside of a form for 'checked' to work.
I had the exact same issue on my branch(lets call it branch B) and I followed three simple steps to get make it work
Now you can delete branch B and then rename branch C to branch B.
Hope this helps.
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
First lets take a look at how can we define a variable in mysql
To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.
Now, how to assign a value in a variable in mysql. For this we have many ways to do that
Example :-
mysql > SET @a = 1;
Example:-
mysql > @a:=1;
Example:-
mysql > select 1 into @a;
Here @a is user defined variable and 1 is going to be assigned in @a.
Now how to get or select the value of @{variable_name}.
we can use select statement like
Example :-
mysql > select @a;
it will show the output and show the value of @a.
Now how to assign a value from a table in a variable.
For this we can use two statement like :-
1.
@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;
Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.
refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql
The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:
> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972
Here is a simple regex which will remove the url("
and ")
from the returned string.
var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");
I've tested various solutions with perfplot (a small project of mine) and found that
numpy.prod(lst)
is by far the fastest solution (if the list isn't very short).
Code to reproduce the plot:
import perfplot
import numpy
import math
from operator import mul
from functools import reduce
from itertools import accumulate
def reduce_lambda(lst):
return reduce(lambda x, y: x * y, lst)
def reduce_mul(lst):
return reduce(mul, lst)
def forloop(lst):
r = 1
for x in lst:
r *= x
return r
def numpy_prod(lst):
return numpy.prod(lst)
def math_prod(lst):
return math.prod(lst)
def itertools_accumulate(lst):
for value in accumulate(lst, mul):
pass
return value
perfplot.show(
setup=numpy.random.rand,
kernels=[reduce_lambda, reduce_mul, forloop, numpy_prod, itertools_accumulate, math_prod],
n_range=[2 ** k for k in range(15)],
xlabel="len(a)",
logx=True,
logy=True,
)
Expanding slightly on @Assaf answer, to apply formatting correctly I also had to convert the DateTime
via the .ToOADate()
function before the formatting took effect. You can do this on a cell by cell basis:
xlWorkSheet.Cells[Row, Col].NumberFormat = "<Required Format>"; // e.g. dd-MMM-yyyy
xlWorkSheet.Cells[Row, Col] = DateTimeObject.ToOADate();
Or you can apply the formatting to the entire column:
xlWorkSheet.Cells[Row, Col].EntireColumn.NumberFormat = "<Required Format>"; // e.g. dd-MMM-yyyy
xlWorkSheet.Cells[Row, Col] = DateTimeObject.ToOADate();
No need of JQuery simply you can do
if(yourObject['email']){
// what if this property exists.
}
as with any value for email
will return you true
, if there is no such property or that property value is null
or undefined
will result to false
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
You can't implicitly return with an if
, you would need the braces:
let adults = family.filter(person => { if (person.age > 18) return person} );
It can be simplified though:
let adults = family.filter(person => person.age > 18);
I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).
In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.
File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.
You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98
Just add 360° if the answer from atan2 is less than 0°.
strftime
(C89)
Martin mentioned it, here's an example:
main.c
#include <assert.h>
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
Compile and run:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Sample output:
Thu Apr 14 22:39:03 2016
The %c
specifier produces the same format as ctime
.
One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:
RETURN VALUE
Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then
strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.
asctime
and ctime
(C89, deprecated in POSIX 7)
asctime
is a convenient way to format a struct tm
:
main.c
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
Sample output:
Wed Jun 10 16:10:32 2015
And there is also ctime()
which the standard says is a shortcut for:
asctime(localtime())
As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.
POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:
The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.
C++ version of this question: How to get current time and date in C++?
Tested in Ubuntu 16.04.
You can use basename()
and $_SERVER['PHP_SELF']
to get current page file name
echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.
.centercol h1{
display: inline-block;
color: #006bb6;
font-weight: normal;
font-size: 18px;
padding:3px 3px 3px 6px;
border-left:3px solid #c6c1b8;
background:#f2efe9;
display:block;
}
This is the complete way to omit unneeded redirects, too ;)
These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
Eplanations:
RewriteEngine on
==> enable the engine at all
RewriteCond %{HTTPS} off [OR]
==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)
RewriteCond %{HTTP:X-Forwarded-Proto} !https
==> match on forwarded connections (proxy, loadbalancer, etc.) without https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.
There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.
Following the instructions here Codesign gdb on macOS seemed to resolve this issue, for me, on macOS High Sierra (10.13.3).
Another DISTINCT
answer, but with multiple values:
SELECT DISTINCT `field1`, `field2`, `field3` FROM `some_table` WHERE `some_field` > 5000 ORDER BY `some_field`
Try reinterpret_cast
unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));
You could translate each string to lowercase once --- lazily only when you need it, or as a prepass to the sort if you know you'll be sorting the entire collection of strings. There are several ways to attach this comparison key to the actual data being sorted, but these techniques should be addressed in a separate issue.
Note that this technique can be used not only to handle upper/lower case issues, but for other types of sorting such as locale specific sorting, or "Library-style" title sorting that ignores leading articles and otherwise normalizes the data before sorting it.
You can do this with dynamic objects:
var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };
foreach(var keyvalue in dynamicKeyValueArray)
{
Console.Log(keyvalue.Key);
Console.Log(keyvalue.Value);
}
I have this error when compiling and bundling TS with WebPack. It compiles export class AppRouterElement extends connect(store, LitElement){....}
into let Sr = class extends (Object(wr.connect) (fn, vr)) {....}
which seems wrong because of missing comma. When bundling with Rollup, no error.
DATE_ADD
works just fine with different months. The problem is that you are adding six months to 2001-01-01
and July 1st is supposed to be there.
This is what you want to do:
SELECT *
FROM mydb
WHERE creationdate BETWEEN "2011-01-01"
AND DATE_ADD("2011-01-01", INTERVAL 6 MONTH) - INTERVAL 1 DAY
GROUP BY MONTH(creationdate)
OR
SELECT *
FROM mydb
WHERE creationdate >= "2011-01-01"
AND creationdate < DATE_ADD("2011-01-01", INTERVAL 6 MONTH)
GROUP BY MONTH(creationdate)
For further learning, take a look at DATE_ADD documentation.
*edited to correct syntax
For UTF-8 textual information, you should use utf8_general_ci
because...
utf8_bin
: compare strings by the
binary value of each character in
the string
utf8_general_ci
: compare strings
using general language rules and
using case-insensitive comparisons
a.k.a. it will should making searching and indexing the data faster/more efficient/more useful.
Just my two sends here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
It will be something like this:
SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
Books b
JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
JOIN Publishers p ON p._PublisherID = b.PublisherID
JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
JOIN Writer w ON w._WritersID = wb._Writers_WriterID
You use the join
statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b
the Books
table will be referred to as b
in the rest of the query. This makes for less typing.
FYI your naming convention is very strange, I would expect it to be more like this:
Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID
Do this to distinguish that.
If for example your number is 3.1214 and stored in num but you don't know kind of num:
num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
// num is a integer
}
else
// num is float
}
In this example we see that num is not integer.
Followint @user1548357 I decided to change the module file itself. So as to avoid the problems pointed out by the valid comments below I included my changes in a postinstall script so that I can set it and forget it and be assured that it will run when my modules are installed.
// package.json
"scripts": {
// other scripts
"postinstall": "node ./bson.fix.js"
},
and the script is:
// bson.fix.js
var fs = require('fs');
var file = './node_modules/bson/ext/index.js'
fs.readFile(file, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/\.\.\/build\/Release\/bson/g, 'bson');
fs.writeFile(file, result, 'utf8', function (err) {
if (err) return console.log(err);
console.log('Fixed bson module so as to use JS version');
});
});
You can always set the options, based on this page you can set, to get rid of the seconds, something like this
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.
The visible width of an element is width + padding + border + outline
, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width
on the input, or making your div wider.
I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.
From within a sbt session:
test:testOnly *YourTestClass
(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass
.)
All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:
test:testQuick
... which will only execute tests that failed. (Repeating the most recently executed test:testOnly
command will be the same as test:testQuick
in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick
a more efficient way to re-run failing tests.)
Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.
If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)
In My case I have't define all variables which I am passing to data in ajax.
var page = 1;
$.ajax({
url: 'your_url',
type: "post",
data: { 'page' : page, 'search_candidate' : search_candidate }
success: function(result){
alert('function called');
}
)}
I have just defined variable var search_candidate = "candidate name";
and its working.
var page = 1;
var search_candidate = "candidate name"; // defined
$.ajax({
url: 'your_url',
type: "post",
data: { 'page' : page, 'search_candidate' : search_candidate }
success: function(result){
alert('function called');
}
)}
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
If you run Ant from eclipse, the eclipse will use jdk or jre that is configured in the class-path(build path).
Here is a quick example:
public class One {
/**
* @param args
*/
public static void main(String[] args) {
double a = 4.56777;
System.out.println( new Float( Math.round(a)) );
}
}
the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double
values and provides whole long
values
Regards
Add the following style to your h3
elements:
word-wrap: break-word;
This will cause the long URLs in them to wrap. The default setting for word-wrap is normal
, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.
Currently there is no better way, however there may be a marginal improvement by moving SaveChanges inside for loop for probably 10 items.
int i = 0;
foreach (Employees item in sequence)
{
t = new Employees ();
t.Text = item.Text;
dataContext.Employees.AddObject(t);
// this will add max 10 items together
if((i % 10) == 0){
dataContext.SaveChanges();
// show some progress to user based on
// value of i
}
i++;
}
dataContext.SaveChanges();
You can adjust 10 to be closer to better performance. It will not greatly improve speed but it will allow you to show some progress to user and make it more user friendly.
This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
Yes not working! I spent whole day with this stupid phpMyAdmin. Just add a new user with a password
1 - Login to mysql or mariadb mysql -u root -p
2 - Run these SQL commands to create a new user with all permissions (or grant your custom permissions)
CREATE USER 'someone'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'someone'@'localhost';
FLUSH PRIVILEGES;
2 - Go to /etc/phpMyAdmin/config.inc.php
and change this:
$cfg['Servers'][$i]['user'] = 'someone';
$cfg['Servers'][$i]['password'] = 'password';
WARNING: This config is for localhost development server only, If you're running a production server you must use strong credentials and not setting user pass in config.inc.php
We can export a jar file for Android library project without resource files by Android studio. It is also requirement what I met recently.
1. Config your build.gradle file
// Task to delete old jar
task clearJar(type: Delete){
delete 'release/lunademo.jar'
}
// task to export contents as jar
task makeJar(type: Copy) {
from ('build/intermediates/bundles/release/')
into ('build/libs/')
include ('classes.jar')
rename('classes.jar', 'lunademo.jar')
}
makeJar.dependsOn(clearJar, build)
2. Run gradlew makeJar under your project root
You will see your libs under dir as build/libs/ if you are luckily.
============================================================
If you met issue as "Socket timeout exception" on command line as below,
You can follow this steps to open Gradle window in the right part and click "makeJar" on Android studio like this,
Then go to build/libs dir, you will see your jar file.
Hope that it is helpful for u.
Good Luck @.@
Luna
The problem is that dataTable
is not defined at the point you are calling this method.
Ensure that you are loading the .js
files in the correct order:
<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc
included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo
as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options
ticks: {
callback: function(value) {
return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'});
},
},
I hope this can be helpful. :)
I. Declaring vars, functions inside IIFE(Immediately-invoked function expression), those can be used only in the anonymous function. (It can be good to use "let, const" keywords without using 'var' when you need to change code for ES6.)
let Name = (function() {
const _privateHello = function() {
}
class Name {
constructor() {
}
publicMethod() {
_privateHello()
}
}
return Name;
})();
II. WeakMap object can be good for memoryleak trouble.
Stored variables in the WeakMap will be removed when the instance will be removed. Check this article. (Managing the private data of ES6 classes)
let Name = (function() {
const _privateName = new WeakMap();
})();
III. Let's put all together.
let Name = (function() {
const _privateName = new WeakMap();
const _privateHello = function(fullName) {
console.log("Hello, " + fullName);
}
class Name {
constructor(firstName, lastName) {
_privateName.set(this, {firstName: firstName, lastName: lastName});
}
static printName(name) {
let privateName = _privateName.get(name);
let _fullname = privateName.firstName + " " + privateName.lastName;
_privateHello(_fullname);
}
printName() {
let privateName = _privateName.get(this);
let _fullname = privateName.firstName + " " + privateName.lastName;
_privateHello(_fullname);
}
}
return Name;
})();
var aMan = new Name("JH", "Son");
aMan.printName(); // "Hello, JH Son"
Name.printName(aMan); // "Hello, JH Son"
You'll need to get those bytes
into a MemoryStream
:
Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
bmp = new Bitmap(ms);
}
That uses the Bitmap(Stream stream)
constructor overload.
UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException
will be thrown on these conditions:
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
These instructions are for windows machine with a single user profile for AWS. Make sure your ~/.aws/credentials
file looks like this
[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey
I had to set the AWS_DEFAULT_PROFILE
environment variable to profile_name
found in your credentials.
Then my python was able to connect. eg from here
import boto3
# Let's use Amazon S3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):
import inspect
import functools
def memoize(fn):
cache = fn.cache = {}
@functools.wraps(fn)
def memoizer(*args, **kwargs):
kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
if key not in cache:
cache[key] = fn(**kwargs)
return cache[key]
return memoizer
Similar question: Identifying equivalent varargs function calls for memoization in Python
Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete()
method of jquery ajax
. I quote the notice on jquery website here:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
To know the status code
of a ajax response, one can use the following code:
$.ajax( url [, settings ] )
.always(function (jqXHR) {
console.log(jqXHR.status);
});
Works similarily for .done()
and .fail()
document.addEventListener('scroll', function (event) {
if ((<HTMLInputElement>event.target).id === 'latest-div') { // or any other filtering condition
}
}, true /*Capture event*/);
You can use this to capture an event and and here "latest-div" is the id name so u can capture all scroller action here based on the id you can do the action as well inside here.
I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.
Here's my solution.
I noticed that when I specify the listbox's rowsource via the properties window in the VBE, the headers pop up no problem. Its only when we try define the rowsource through VBA code that the headers get lost.
So I first went a defined the listboxes rowsource as a named range in the VBE for via the properties window, then I can reset the rowsource in VBA code after that. The headers still show up every time.
I am using this in combination with an advanced filter macro from a listobject, which then creates another (filtered) listobject on which the rowsource is based.
This worked for me
Make sure your id_rsa file doesn't have any extension like .txt or .rtf. Rich Text Format adds additional characters to your file and those gets added to byte array. Which eventually causes invalid private key error. Long story short, Copy the file, not content.
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).
There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.
You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).
Yo can use:
a.update_column :state, a.state
Check: http://apidock.com/rails/ActiveRecord/Persistence/update_column
Updates a single attribute of an object, without calling save.
With zsh you can do this:
% cat infile
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class
Or you can use AWK:
% awk '!_[$0]++' infile
tar
more than one word
gz
java
class
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
Importing inside a function will effectively import the module once.. the first time the function is run.
It ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours...
If that's not he reason you're doing this, it's almost certainly a yucky idea.
Old question but this answer might help someone.
If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden
, otherwise anything outside of it will be cut off.
When we save anything in Django admin two steps validation happens, on Django level and on Database level. We can't save text in a number field.
Database has data type NULL, it's nothing. When Django creates columns in the database it specifies that they can't be empty. And if you will try to save NULL you will get the database error.
Also on Django-Admin level, all fields are required by default, you can't save blank field, Django will throw you an error.
So, if you want to save blank field you need to allow it on Django and Database level. blank=True - will allow empty field in admin panel null=True - will allow saving NULL to the database column.
After having looked at various versions of itoa for gcc, the most flexible version I have found that is capable of handling conversions to binary, decimal and hexadecimal, both positive and negative is the fourth version found at http://www.strudel.org.uk/itoa/. While sprintf
/snprintf
have advantages, they will not handle negative numbers for anything other than decimal conversion. Since the link above is either off-line or no longer active, I've included their 4th version below:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
I think the answer depends on which features of stored procedures you need to use.
Stored procedures returning a result set can be run using Query
; stored procedures which don't return a result set can be run using Execute
- in both cases (using EXEC <procname>
) as the SQL command (plus input parameters as necessary). See the documentation for more details.
As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT
parameters; you could add this, or alternatively construct a more complex Query
command which declared TSQL variables, executed the SP collecting OUTPUT
parameters into the local variables and finallyreturned them in a result set:
DECLARE @output int
EXEC <some stored proc> @i = @output OUTPUT
SELECT @output AS output1
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
I've seen this pattern several times:
>>> class Enumeration(object):
def __init__(self, names): # or *names, with no .split()
for number, name in enumerate(names.split()):
setattr(self, name, number)
>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2
You can also just use class members, though you'll have to supply your own numbering:
>>> class Foo(object):
bar = 0
baz = 1
quux = 2
>>> Foo.quux
2
If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.
<EditText
android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:imeOptions="actionSend" />
You can then listen for presses on the action button by defining a TextView.OnEditorActionListener for the EditText element. In your listener, respond to the appropriate IME action ID defined in the EditorInfo class, such as IME_ACTION_SEND. For example:
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendMessage();
handled = true;
}
return handled;
}
});
Source: https://developer.android.com/training/keyboard-input/style.html
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
Better to use a vbs as you indicated
vbs
, which is a text file with a .vbs extension (see sample code below)vbs
vbs
to open the workbook
at the scheduled time and then either:
Private Sub Workbook_Open()
event in the ThisWorkbook
module to run code when the file is openedApplication.Run
in the vbs
to run the macroSee this example of the later approach at Running Excel on Windows Task Scheduler
sample vbs
Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run
ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing
+1 for print_r(). Use it to dump out the contents of an object or variable. To make it more readable, do it with a pre tag so you don't need to view source.
echo '<pre>';
print_r($arrayOrObject);
Also var_dump($thing) - this is very useful to see the type of subthings
So, I tried these other ways, but there was a VERY slight irritant and that was if you keep the modal-content border radius, in FF and Chrome, there is a slight bit of white trim showing along the borders, even if you use 5px on the modal-header border radius. (standard modal-content border radius is 6px, so 5px on the modal-header border top radius covers some white).
My solution:
.modal-body
{
background-color: #FFFFFF;
}
.modal-content
{
border-radius: 6px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
background-color: transparent;
}
.modal-footer
{
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
-webkit-border-bottom-left-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
-moz-border-radius-bottomleft: 6px;
-moz-border-radius-bottomright: 6px;
}
.modal-header
{
border-top-left-radius: 6px;
border-top-right-radius: 6px;
-webkit-border-top-left-radius: 6px;
-webkit-border-top-right-radius: 6px;
-moz-border-radius-topleft: 6px;
-moz-border-radius-topright: 6px;
}
!! CAVEAT !!
You must then set the background colors of the modal-header, modal-content, and modal-footer. This is not bad trade-off, because it allows you to do this:
<div class="modal-header bg-primary">
<div class="modal-body bgColorWhite">
<div class="modal-footer bg-info">
EDIT
Or even better:
<div class="modal-header alert-primary">
We use groovy job file:
description('')
steps {
environmentVariables {
envs(PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true)
}
}
I normally have them in an array and call writeBooleanArray
and readBooleanArray
If it's a single boolean you need to pack, you could do this:
parcel.writeBooleanArray(new boolean[] {myBool});
Python includes a function called itemgetter to return the item at a specific index in a list:
from operator import itemgetter
Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:
itemgetter(0)([10, 20, 30]) # Returns 10
This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:
my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']
Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:
lst2.append(list(map(itemgetter(0), lst)))
This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.
More info: https://docs.python.org/3/library/operator.html#operator.itemgetter
If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}
Yes you can use CASE
UPDATE table
SET columnB = CASE fieldA
WHEN columnA=1 THEN 'x'
WHEN columnA=2 THEN 'y'
ELSE 'z'
END
WHERE columnC = 1
Interestingly, when I replaced this:
$("body").trigger("click")
With this:
jQuery("body").trigger("click")
It works!
Try this function isLayoutSizeAtLeast(int screenSize)
To check small screen, atleast 320x426 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL);
To check normal screen, atleast 320x470 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL);
To check large screen, atleast 480x640 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);
To check extra large screen, atleast 720x960 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE);
This is what worked for me (Refer to image linked)
For future reference, you can find the folder your packages are downloading to if you happen to have a requirement already satisfied. You can see it if you scroll up in the terminal. It should read something like: requirement already satisfied and then the path
[]
Swift 2.0 :
1)
if let url = NSURL(string: "http://etc...") {
if let data = NSData(contentsOfURL: url) {
imageURL.image = UIImage(data: data)
}
}
OR
imageURL.image =
NSURL(string: "http:// image name...")
.flatMap { NSData(contentsOfURL: $0) }
.flatMap { UIImage(data: $0) }
2) Add this method to VC or Extension.
func load_image(urlString:String)
{ let imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in
if error == nil {
self.image_element.image = UIImage(data: data)
}
}
}
Usage :
self.load_image(" url strig here")
position: fixed;
will also "pop" an element out of the flow, as you say. :)
position: absolute
must be accompanied by a position. e.g. top: 1rem; left: 1rem
position: fixed
however, will place the element where it would normally appear according to the document flow, but prevent it from moving after that. It also effectively set's the height to 0px (with regards to the dom) so that the next element shifts up over it.
This can be pretty cool, because you can set position: fixed; z-index: 1
(or whatever z-index you need) so that it "pops" over the next element.
This is especially useful for fixed position headers that stay at the top when you scroll, for example.
Put the divisions in 'td' tag. That's it done.
This is the best code to calculate year and month difference:
DateTime firstDate = DateTime.Parse("1/31/2019");
DateTime secondDate = DateTime.Parse("2/1/2016");
int totalYears = firstDate.Year - secondDate.Year;
int totalMonths = 0;
if (firstDate.Month > secondDate.Month)
totalMonths = firstDate.Month - secondDate.Month;
else if (firstDate.Month < secondDate.Month)
{
totalYears -= 1;
int monthDifference = secondDate.Month - firstDate.Month;
totalMonths = 12 - monthDifference;
}
if ((firstDate.Day - secondDate.Day) == 30)
{
totalMonths += 1;
if (totalMonths % 12 == 0)
{
totalYears += 1;
totalMonths = 0;
}
}
At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).
Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.
Here is a general solution that may be applied along an axis, regardless of values, using purely numpy. I've also found that this is much faster than scipy.stats.mode if there are a lot of unique values.
import numpy
def mode(ndarray, axis=0):
# Check inputs
ndarray = numpy.asarray(ndarray)
ndim = ndarray.ndim
if ndarray.size == 1:
return (ndarray[0], 1)
elif ndarray.size == 0:
raise Exception('Cannot compute mode on empty array')
try:
axis = range(ndarray.ndim)[axis]
except:
raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))
# If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
if all([ndim == 1,
int(numpy.__version__.split('.')[0]) >= 1,
int(numpy.__version__.split('.')[1]) >= 9]):
modals, counts = numpy.unique(ndarray, return_counts=True)
index = numpy.argmax(counts)
return modals[index], counts[index]
# Sort array
sort = numpy.sort(ndarray, axis=axis)
# Create array to transpose along the axis and get padding shape
transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
shape = list(sort.shape)
shape[axis] = 1
# Create a boolean array along strides of unique values
strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
numpy.diff(sort, axis=axis) == 0,
numpy.zeros(shape=shape, dtype='bool')],
axis=axis).transpose(transpose).ravel()
# Count the stride lengths
counts = numpy.cumsum(strides)
counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
counts[strides] = 0
# Get shape of padded counts and slice to return to the original shape
shape = numpy.array(sort.shape)
shape[axis] += 1
shape = shape[transpose]
slices = [slice(None)] * ndim
slices[axis] = slice(1, None)
# Reshape and compute final counts
counts = counts.reshape(shape).transpose(transpose)[slices] + 1
# Find maximum counts and return modals/counts
slices = [slice(None, i) for i in sort.shape]
del slices[axis]
index = numpy.ogrid[slices]
index.insert(axis, numpy.argmax(counts, axis=axis))
return sort[index], counts[index]
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
If we need to show different type of view in list-view then its good to use getViewTypeCount() and getItemViewType() in adapter instead of toggling a view VIEW.GONE and VIEW.VISIBLE can be very expensive task inside getView() which will affect the list scroll.
Please check this one for use of getViewTypeCount() and getItemViewType() in Adapter.
Link : the-use-of-getviewtypecount
In our case problem was caused by IIS server certificate. The certificate's subject was set to DNS name and users were trying to access web site by IP adress, so .NET certification validation failed. Problem disappeared when users started to use DNS name.
So you have to change your Provider URL to https://CertificateSubject/xxx/xxx.application
You can also just do this in all the activities that you dont want to transition from:
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
I like this approach because you do not have to mess with the style of your activity.
Just an information: let us all remember that the Image
class is actually an abstract class and referencing a variable of this with a BufferedImage only stores or returns any Object's memory adress.
Also, wherefore, static java.awt.image.imageIO
's read()
method returns a BufferedImage
object, therefore no doubt that using operator/expression instanceof BufferedImage
on that object will return true
.
In fact, being abstract, Image
class has such method signatures as:
public abstract Graphics getGraphics()
public abstract ImageProducer getSource()
among others.
I emphasize, an actual Image
variable only holds memory adress of a concrete Image-subclass object, almost like pointers in C, C++, Ada, etc.
If you're introduced or advanced in those languages, and also of Java interface instances like Runnable
, javax.sound.Clip
, AWT's Shape
, etc.. . Take note that Image
has: public abstract Image getScaledInstance(...)
- you get the point. (Of course, scaling in 2D Graphics programming is interchangeable to resizing, for which precision is desirable).
But in an impossible case when herein ImageIO method return ! (instanceof BufferedImage)
just create a new BufferedImage
object with this ImgObjNotInstncfBufImg
apassed to one of its constructor argument. Then, at (rational) will manipulate this in the logic of your code.
Anyways, the Affine Transform class is appropriate for transforming Shapes and Images to thier scaled, rotated, relocated, etc forms, so I recommend you to study about using an "affine transform".
Take note that you can manipulate the actual pixels in such Image's Raster - well another technical 2D Graphics jargon which must be referenced from a technical glossary - which perhaps a excercised skill in Java ways of binary blitwise operations will be needed, in types of Image buffers that store individual color attributes in a compact in of 32-bytes - 7-bits each for the alpha and RGB values.
I suspect your gonna use it in layering images. So, FINALLY, the rational is that you only reference BufferedImage
with the abstract Image, and if ever your Image
object isn't a BufferedImage
one yet, then you can just make an image out of this related-but-non-BufferedImage-instance without having to worry about any conversion, casting, autoboxing or whatever; manipulating a BufferedImage really means manipulating also the underlying root Image data-bearing object that it points to.
Okay, finished; I think I certainly extracted and splintered out what deadlock you may have thought you are facing to. As I have said abstract classes in java, and also interfaces, are very much the equivaleng of the low-level, more-close-to-hardware operators called pointers in other languages.
The only effect of choosing a branch for a submodule is that, whenever you pass the --remote
option in the git submodule update
command line, Git will check out in detached HEAD mode (if the default --checkout
behavior is selected) the latest commit of that selected remote branch.
You must be particularly careful when using this remote branch tracking feature for Git submodules if you work with shallow clones of submodules.
The branch you choose for this purpose in submodule settings IS NOT the one that will be cloned during git submodule update --remote
.
If you pass also the --depth
parameter and you do not instruct Git about which branch you want to clone -- and actually you cannot in the git submodule update
command line!! -- , it will implicitly behave like explained in the git-clone(1)
documentation for git clone --single-branch
when the explicit --branch
parameter is missing, and therefore it will clone the primary branch only.
With no surprise, after the clone stage performed by the git submodule update
command, it will finally try to check out the latest commit for the remote branch you previously set up for the submodule, and, if this is not the primary one, it is not part of your local shallow clone, and therefore it will fail with
fatal: Needed a single revision
Unable to find current origin/NotThePrimaryBranch revision in submodule path 'mySubmodule'
this
reference a javascript object and $(this)
used to encapsulate with jQuery.
Example =>
// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')
// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)
// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()
//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()
//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value
or
this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')
C# is a programming language.
.Net is a framework used for building applications on Windows.
.Net framework is not limited to C#. Different languages can target .Net framework and build applications using that framework. Examples are F# or VB.Net
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return
statement
create proc myproc
as
begin
return 1
end
go
declare @i int
exec @i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
@a int output,
@b varchar(50) output
as
begin
select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare @t table (name varchar(100))
insert @t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
I had the same problem try this:
python manage.py sqlsequencereset table_name
Eg:
python manage.py sqlsequencereset auth
you need to run this in production settings(if you have) and you need Postgres installed to run this on the server
I had the same problem: I love the resolve
object, but that only works for the content of ng-view. What if you have controllers (for top-level nav, let's say) that exist outside of ng-view and which need to be initialized with data before the routing even begins to happen? How do we avoid mucking around on the server-side just to make that work?
Use manual bootstrap and an angular constant. A naiive XHR gets you your data, and you bootstrap angular in its callback, which deals with your async issues. In the example below, you don't even need to create a global variable. The returned data exists only in angular scope as an injectable, and isn't even present inside of controllers, services, etc. unless you inject it. (Much as you would inject the output of your resolve
object into the controller for a routed view.) If you prefer to thereafter interact with that data as a service, you can create a service, inject the data, and nobody will ever be the wiser.
Example:
//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);
// Use angular's version of document.ready() just to make extra-sure DOM is fully
// loaded before you bootstrap. This is probably optional, given that the async
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope.
angular.element(document).ready(function() {
//first, we create the callback that will fire after the data is down
function xhrCallback() {
var myData = this.responseText; // the XHR output
// here's where we attach a constant containing the API data to our app
// module. Don't forget to parse JSON, which `$http` normally does for you.
MyApp.constant('NavData', JSON.parse(myData));
// now, perform any other final configuration of your angular module.
MyApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/someroute', {configs})
.otherwise({redirectTo: '/someroute'});
}]);
// And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
angular.bootstrap(document, ['NYSP']);
};
//here, the basic mechanics of the XHR, which you can customize.
var oReq = new XMLHttpRequest();
oReq.onload = xhrCallback;
oReq.open("get", "/api/overview", true); // your specific API URL
oReq.send();
})
Now, your NavData
constant exists. Go ahead and inject it into a controller or service:
angular.module('MyApp')
.controller('NavCtrl', ['NavData', function (NavData) {
$scope.localObject = NavData; //now it's addressable in your templates
}]);
Of course, using a bare XHR object strips away a number of the niceties that $http
or JQuery would take care of for you, but this example works with no special dependencies, at least for a simple get
. If you want a little more power for your request, load up an external library to help you out. But I don't think it's possible to access angular's $http
or other tools in this context.
(SO related post)
A variation on the MutableInt approach that might be even faster, if a bit of a hack, is to use a single-element int array:
Map<String,int[]> map = new HashMap<String,int[]>();
...
int[] value = map.get(key);
if (value == null)
map.put(key, new int[]{1} );
else
++value[0];
It would be interesting if you could rerun your performance tests with this variation. It might be the fastest.
Edit: The above pattern worked fine for me, but eventually I changed to use Trove's collections to reduce memory size in some very large maps I was creating -- and as a bonus it was also faster.
One really nice feature is that the TObjectIntHashMap
class has a single adjustOrPutValue
call that, depending on whether there is already a value at that key, will either put an initial value or increment the existing value. This is perfect for incrementing:
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
...
map.adjustOrPutValue(key, 1, 1);
There is nothing available that I'm aware of. The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option.
See if the below helps you:
I was using the following earlier:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");
After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:
ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);
This is working perfectly fine.
(It’s .NET 2.0 Framework, I am using)
You can use the DateTime
class:
$past = new DateTime("2010-01-01 00:00:00");
$now = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");
Comparison operators work*:
var_dump($past < $now); // bool(true)
var_dump($future < $now); // bool(false)
var_dump($now == $past); // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future); // bool(false)
var_dump($past > $now); // bool(false)
var_dump($future > $now); // bool(true)
It is also possible to grab the timestamp values from DateTime objects and compare them:
var_dump($past ->getTimestamp()); // int(1262286000)
var_dump($now ->getTimestamp()); // int(1431686228)
var_dump($future->getTimestamp()); // int(1577818800)
var_dump($past ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
* Note that ===
returns false when comparing two different DateTime objects even when they represent the same date.
In C++20 one can default operator<=> without a user-defined comparator. The compiler will take care of that.
#include <iostream>
#include <compare>
#include <vector>
#include <algorithm>
struct MyInt
{
int value;
MyInt(int val) : value(val) {}
auto operator<=>(const MyInt& other) const = default;
};
int main()
{
MyInt Five(5);
MyInt Two(2);
MyInt Six(6);
std::vector V{Five, Two, Six};
std::sort(V.begin(), V.end());
for (const auto& element : V)
std::cout << element.value << std::endl;
}
Output:
2
5
6
The code seems to be flawless!
Simple and plain.
So it should work on the phone. The emulator is having hard time playing videos, it happened to me too.
Try increasing the required API level to the latest, it might help!
Right click on opened project, chose Properties > Android > check the latest version on the right side...
Igor
tick_params is very useful for setting tick properties. Labels can be moved to the top with:
ax.tick_params(labelbottom=False,labeltop=True)
For those of you wishing not to use an external library, and prefer not to use OleDB, see the example below. Everything I found was either OleDB, external library, or simply splitting based on a comma! For my case OleDB was not working so I wanted something different.
I found an article by MarkJ that referenced the Microsoft.VisualBasic.FileIO.TextFieldParser method as seen here. The article is written in VB and doesn't return a datatable, so see my example below.
public static DataTable LoadCSV(string path, bool hasHeader)
{
DataTable dt = new DataTable();
using (var MyReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(path))
{
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
MyReader.Delimiters = new String[] { "," };
string[] currentRow;
//'Loop through all of the fields in the file.
//'If any lines are corrupt, report an error and continue parsing.
bool firstRow = true;
while (!MyReader.EndOfData)
{
try
{
currentRow = MyReader.ReadFields();
//Add the header columns
if (hasHeader && firstRow)
{
foreach (string c in currentRow)
{
dt.Columns.Add(c, typeof(string));
}
firstRow = false;
continue;
}
//Create a new row
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
//Loop thru the current line and fill the data out
for(int c = 0; c < currentRow.Count(); c++)
{
dr[c] = currentRow[c];
}
}
catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex)
{
//Handle the exception here
}
}
}
return dt;
}
It is amusing to return 418 I'm a teapot
to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.
2.3.2 418 I'm a teapot
Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Sounds like your initialized AudioElement
class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress
in state.
You can either initialize the AudioElement
class object in a new React component or just convert that class to a React component.
class MyAudioPlayer extends React.Component {
constructor(props) {
super(props);
this.player = new AudioElement('test.mp3');
this.player.audio.ontimeupdate = this.updateProgress;
}
updateProgress () {
// Dispatch action to reducer with updated progress.
// You might want to actually send the current time and do the
// calculation from within the reducer.
this.props.updateProgressAction();
}
render () {
// Render the audio player controls, progress bar, whatever else
return <p>Progress: {this.props.progress}</p>;
}
}
class MyContainer extends React.Component {
render() {
return <MyAudioPlayer updateProgress={this.props.updateProgress} />
}
}
function mapStateToProps (state) { return {}; }
return connect(mapStateToProps, {
updateProgressAction
})(MyContainer);
Note that the updateProgressAction
is automatically wrapped with dispatch
so you don't need to call dispatch directly.
x=[]
x = [int(i) for i in input().split()]
i = 0
while i < len(x):
print(x[i])
if(x[i]%5)==0:
del x[i]
else:
i += 1
print(*x)
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
//this should allow you to replica an animation effect for any css property, even //properties //that transform animation jQuery plugins do not allow
function twistMyElem(){
var ball = $('#form');
document.getElementById('form').style.zIndex = 1;
ball.animate({ zIndex : 360},{
step: function(now,fx){
ball.css("transform","rotateY(" + now + "deg)");
},duration:3000
}, 'linear');
}
I chose to rename all instances instead of destroy/replace - since sometimes the AJAX loaded instance doesn't really replace the one on the core of the page... keeps more in RAM, but less conflict this way.
if (CKEDITOR && CKEDITOR.instances) {
for (var oldName in CKEDITOR.instances) {
var newName = "ajax"+oldName;
CKEDITOR.instances[newName] = CKEDITOR.instances[oldName];
CKEDITOR.instances[newName].name = newName;
delete CKEDITOR.instances[oldName];
}
}
My lightweight implementation of ParallelForEach async.
Features:
public static class AsyncEx
{
public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
{
var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
var tcs = new TaskCompletionSource<object>();
var exceptions = new ConcurrentBag<Exception>();
bool addingCompleted = false;
foreach (T item in source)
{
await semaphoreSlim.WaitAsync();
asyncAction(item).ContinueWith(t =>
{
semaphoreSlim.Release();
if (t.Exception != null)
{
exceptions.Add(t.Exception);
}
if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
{
tcs.TrySetResult(null);
}
});
}
Volatile.Write(ref addingCompleted, true);
await tcs.Task;
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
}
Usage example:
await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
var data = await GetData(i);
}, maxDegreeOfParallelism: 100);
You can use the --prefix
option:
mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>
The package(s) will then be installed in ./install/here/node_modules
. The mkdir
is needed since npm might otherwise choose an already existing node_modules
directory higher up in the hierarchy. (See npm documentation on folders.)
Several answers show dangerous examples. OP's example [ $a == $b ]
specifically used unquoted variable substitution (as of Oct '17 edit). For [...]
that is safe for string equality.
But if you're going to enumerate alternatives like [[...]]
, you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").
Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:
$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$
The one I always use is here http://blog.neutrino.es/2012/git-copy-a-file-or-directory-from-another-repository-preserving-history/ . Simple and fast.
For compliance with stackoverflow standards, here is the procedure:
mkdir /tmp/mergepatchs
cd ~/repo/org
export reposrc=myfile.c #or mydir
git format-patch -o /tmp/mergepatchs $(git log $reposrc|grep ^commit|tail -1|awk '{print $2}')^..HEAD $reposrc
cd ~/repo/dest
git am /tmp/mergepatchs/*.patch
This page tell that using "::" will be faster under certain constraints Just a thing to consider when choosing
Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.
And so having PDB improves crash reporting.
Keep package name same in manifest file and in build.gradle(Module:app).it resolved my problem.
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Note: Apply the class info_link
to any link you want to get the info from.
<a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
~/Resumes/Resumes1271354404687.docx
</a>
For href:
$(function(){
$('.info_link').click(function(){
alert($(this).attr('href'));
// or alert($(this).hash();
});
});
For Text:
$(function(){
$('.info_link').click(function(){
alert($(this).text());
});
});
.
You can get them like this now:
For href:
$(function(){
$('div.res a').click(function(){
alert($(this).attr('href'));
// or alert($(this).hash();
});
});
For Text:
$(function(){
$('div.res a').click(function(){
alert($(this).text());
});
});
You are trying to access the first element lstpp.get(0)
of an empty array. Just add an element to your array and check for !lstpp.isEmpty()
before accessing an element
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g
and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
You can make method which return the datatable of given sql query:
public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
and now can be used like this:
table = GetDataTable();
There's a Windows answer, and a Debian answer, so here's a Mac one:
This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:
os.system( "say beep" )
Disclaimer: You can replace os.system
with a call to the subprocess
module if you're worried about someone hacking on your beep code.
This is all you need to do:
var myVariable;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'html',
'url': "ajax.php?first",
'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
'success': function (data) {
myVariable = data;
}
});
NOTE: Use of "async" has been depreciated. See https://xhr.spec.whatwg.org/.
On a related note, you may also like:
shopt -s autocd
This allows you to cd a dir by just typing in the dir
[user@host ~]$ /cygdrive/d
cd /cygdrive/d
[user@host /cygdrive/d]$
To make is persistent you should add it to your ~/.bashrc
You can create a jQuery object from a JSON object:
$.getJSON(url, data, function(json) {
$(json).each(function() {
/* YOUR CODE HERE */
});
});
Create a lookup table first:
morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
morse[ord(line[0].lower()) - ord('a')] = line[2:]
Then convert using the table:
for ch in userInput:
print morse[ord(ch.lower()) - ord('a')]
Selenium2Library has get_location():
import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()
You can use %
:
SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'
split doesn't work that way in groovy. you have to use tokenize...
See the docs:
You can simplify to:
WHERE a.Country = COALESCE(NULLIF(@Country,0), a.Country);
Not sure whether this is still actual.. just for future readers. If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().
If you want to open multiple workspaces and you are not a terminal guy, just locate the Unix executable file in your eclipse folder and click it.
The path to the said file is
Eclipse(folder) -> eclipse(right click) -> Show package Contents -> Contents -> MacOs -> eclipse(unix executable file)
Clicking on this executable will open a separate instance of eclipse.
Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o
or netstat -ab
, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.
I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.
Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.
The issue could be that the VM is connected to the network via NAT. You need to set the network adapter of the VM to a bridged connection so that the VM will get it's own IP within the actual network and not on the LAN on the host.
I always used APC with php 5.1 and 5.2, but I had a lot of (random) errors using APC with php 5.3: Strange blank pages, random out-of-memory errors. They all disappeared when I disabled APC. But that was no option, as it is running a high-volume website.
So I tried eaccelerator. So far it has been rock solid and the speed increase is even bigger than with APC. The APC guys really need to spend some time on bugfixing.
Clear the form as follows
document.forms[0].reset();
You can simply clear the form elements within the group. by using this forms[0]
.
DECLARE @vi INT
DECLARE @vQuery NVARCHAR(1000)
SET @vQuery = N'SELECT @vi= COUNT(*) FROM <TableName>'
EXEC SP_EXECUTESQL
@Query = @vQuery
, @Params = N'@vi INT OUTPUT'
, @vi = @vi OUTPUT
SELECT @vi
If all the previous solutions haven't worked for you (which was my case), you can delete intellij config files:
Intellij will regenerate new ones later. However, BE CAREFUL, this will also delete all intellij configuration made on the projet (i.e: configuration of debug mode, ...)
Nowadays, in Python 2.7 and up, you can use a dict comprehension:
{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
And in Python 3:
{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
In phpMyAdmin you can select multiple rows and can then click the delete action. You'll enter a screen which lists the delete queries. It looks like this:
Please uncheck the "Enable foreign key checks" checkbox, and click on Yes to execute them.
This will enable you to delete rows even if there is an ON DELETE restriction constraint.
You can get the current route using
const currentRoute = this.props.routes[this.props.routes.length - 1];
...which gives you access to the props from the lowest-level active <Route ...>
component.
Given...
<Route path="childpath" component={ChildComponent} />
currentRoute.path
returns 'childpath'
and currentRoute.component
returns function _class() { ... }
.
Update for Swift 3.0+
func SYSTEM_VERSION_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedSame
}
func SYSTEM_VERSION_GREATER_THAN(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedDescending
}
func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}
func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedAscending
}
func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedDescending
}
TL;DR: Use __builtin
intrinsics instead; they might happen to help.
I was able to make gcc
4.8.4 (and even 4.7.3 on gcc.godbolt.org) generate optimal code for this by using __builtin_popcountll
which uses the same assembly instruction, but gets lucky and happens to make code that doesn't have an unexpectedly long loop-carried dependency because of the false dependency bug.
I am not 100% sure of my benchmarking code, but objdump
output seems to share my views. I use some other tricks (++i
vs i++
) to make the compiler unroll loop for me without any movl
instruction (strange behaviour, I must say).
Results:
Count: 20318230000 Elapsed: 0.411156 seconds Speed: 25.503118 GB/s
Benchmarking code:
#include <stdint.h>
#include <stddef.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
uint64_t builtin_popcnt(const uint64_t* buf, size_t len){
uint64_t cnt = 0;
for(size_t i = 0; i < len; ++i){
cnt += __builtin_popcountll(buf[i]);
}
return cnt;
}
int main(int argc, char** argv){
if(argc != 2){
printf("Usage: %s <buffer size in MB>\n", argv[0]);
return -1;
}
uint64_t size = atol(argv[1]) << 20;
uint64_t* buffer = (uint64_t*)malloc((size/8)*sizeof(*buffer));
// Spoil copy-on-write memory allocation on *nix
for (size_t i = 0; i < (size / 8); i++) {
buffer[i] = random();
}
uint64_t count = 0;
clock_t tic = clock();
for(size_t i = 0; i < 10000; ++i){
count += builtin_popcnt(buffer, size/8);
}
clock_t toc = clock();
printf("Count: %lu\tElapsed: %f seconds\tSpeed: %f GB/s\n", count, (double)(toc - tic) / CLOCKS_PER_SEC, ((10000.0*size)/(((double)(toc - tic)*1e+9) / CLOCKS_PER_SEC)));
return 0;
}
Compile options:
gcc --std=gnu99 -mpopcnt -O3 -funroll-loops -march=native bench.c -o bench
GCC version:
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
Linux kernel version:
3.19.0-58-generic
CPU information:
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 70
model name : Intel(R) Core(TM) i7-4870HQ CPU @ 2.50 GHz
stepping : 1
microcode : 0xf
cpu MHz : 2494.226
cache size : 6144 KB
physical id : 0
siblings : 1
core id : 0
cpu cores : 1
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm arat pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid xsaveopt
bugs :
bogomips : 4988.45
clflush size : 64
cache_alignment : 64
address sizes : 36 bits physical, 48 bits virtual
power management:
Limit the number of words with a custom Angular filter: Here is how I used an Angular filter to limit the number of words displayed using a custom filter.
HTML:
<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>
Angular/Javascript Code
angular.module('app')
.filter('limitWordsTo', function () {
return function (stringData, numberOfWords) {
//Get array of words (determined by spaces between words)
var arrayOfWords = stringData.split(" ");
//Get loop limit
var loopLimit = numberOfWords > arrayOfWords.length ? arrayOfWords.length : numberOfWords;
//Create variables to hold limited word string and array iterator
var limitedString = '', i;
//Create limited string bounded by limit passed in
for (i = 0; i < loopLimit; i++) {
if (i === 0) {
limitedString = arrayOfWords[i];
} else {
limitedString = limitedString + ' ' + arrayOfWords[i];
}
}
return limitedString;
};
}); //End filter
We had trouble finding one that worked the way we wanted it to so I wrote one. I maintain the source and fix bugs as they arise plus provide free support.
http://www.yart.com.au/Resources/Programming/ASP-NET-JQuery-Date-Time-Control.aspx
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
Be aware of number of digits in epoch time. Usually they are ten (1534936923) ,then use:
=(A1 / 86400) + 25569
For thirteen digits (1534936923000) of epoch time adjust the formula:
=(LEFT(A1,LEN(A1)-3) / 86400) + 25569
to avoid
###################################
Dates or times that are negative or too large display as ######
See more on https://www.epochconverter.com/
You might check Select2 plugin:
http://ivaynberg.github.io/select2/
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.
It's quite popular and very maintainable. It should cover most of your needs if not all.
It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
Where ws
is a Worksheet object. In the questions example it was implied that the statement was inside a With
block
With ws
lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
ws.Rows.Count
returns the total count of rows in the worksheet (1048576 in Excel 2010)..Cells(.Rows.Count, "A")
returns the bottom most cell in column "A" in the worksheetThen there is the End
method. The documentation is ambiguous as to what it does.
Returns a Range object that represents the cell at the end of the region that contains the source range
Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:
rng.cells(1,1)
. So Range.End
is not a trivial function.
.row
returns the row index of that cell....and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.
Thank you guys! :-)
#include <fstream>
ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
getline(infile,data);
}
infile.close();
"validate Email"-Solution for Swift 4: Create this class:
import Foundation
public class EmailAddressValidator {
public init() {
}
public func validateEmailAddress(_ email: String) -> Bool {
let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)
return emailTest.evaluate(with: email)
}
}
private extension String {
static let emailValidationRegEx = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
"9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
}
and use it like this:
let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("[email protected]")
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
@kajetons' answer is fully functional.
You can also pass multiple variables by passing them like: use($var1, $var2)
DB::table('users')->where(function ($query) use ($activated,$var2) {
$query->where('activated', '=', $activated);
$query->where('var2', '>', $var2);
})->get();
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath()
will give you the absolute path, making it usable.
There are three floating point types:
A simple Venn diagram will explain about: The set of values of the types
This is the result from
library(scales)
show_col(hue_pal()(4))
show_col(hue_pal()(3))
import { combineReducers } from '../../store/reducers';
should be
import combineReducers from '../../store/reducers';
since it's a default export, and not a named export.
There's a good breakdown of the differences between the two here.
It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary +
[docs]:
value = +value;
If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then
input.value = +input.value;
is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.
To refresh menu from Fragment simply call:
getActivity().invalidateOptionsMenu();
Cut the long story short: With relative layout you position elements inside the layout.
create a new RelativeLayout.LayoutParams
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(...)
(whatever... fill parent or wrap content, absolute numbers if you must, or reference to an XML resource)
Add rules: Rules refer to the parent or to other "brothers" in the hierarchy.
lp.addRule(RelativeLayout.BELOW, someOtherView.getId())
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
Just apply the layout params: The most 'healthy' way to do that is:
parentLayout.addView(myView, lp)
Watch out: Don't change layout from the layout callbacks. It is tempting to do so because this is when views get their actual sizes. However, in that case, unexpected results are expected.
Have you tried using the generic DeserializeObject method?
JsonConvert.DeserializeObject<MyAccount>(myjsondata);
Any missing fields in the JSON data should simply be left NULL.
UPDATE:
If the JSON string is an array, try this:
var jarray = JsonConvert.DeserializeObject<List<MyAccount>>(myjsondata);
jarray
should then be a List<MyAccount>
.
ANOTHER UPDATE:
The exception you're getting isn't consistent with an array of objects- I think the serializer is having problems with your Dictionary-typed accountstatusmodifiedby
property.
Try excluding the accountstatusmodifiedby
property from the serialization and see if that helps. If it does, you may need to represent that property differently.
Documentation: Serializing and Deserializing JSON with Json.NET
Using UIApplication.openSettingsURLString
Update for Swift 5.1
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
Swift 4.2
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
There is an experimental webkit property called text-stroke
in CSS3, I've been trying to get this to work for some time but have been unsuccessful so far.
What I have done instead is used the already supported text-shadow
property (supported in Chrome, Firefox, Opera, and IE 9 I believe).
Use four shadows to simulate a stroked text:
.strokeme {_x000D_
color: white;_x000D_
text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;_x000D_
}
_x000D_
<div class="strokeme">_x000D_
This text should have a stroke in some browsers_x000D_
</div>
_x000D_
I have made a demo for you here
And a hovered example is available here
As Jason C has mentioned in the comments, the text-shadow
CSS property is now supported by all major browsers, with the exception of Opera Mini. Where this solution will work for backwards compatibility (not really an issue regarding browsers that auto-update) I believe the text-stroke
CSS should be used.
By default Bootstrap javascript files are included just before the closing body tag
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
</body>
I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
<script type="text/javascript">
function openModal() {
$('#myModal').modal('show');
}
</script>
</head>
<body>
then I could call the modal popup from code-behind with the following:
protected void lbEdit_Click(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}
Whenever you don't have access to documentation (SVNBook), type (Linux):
svn help status | grep \'\?\'
svn help status | grep \'\!\'
svn help status | grep \'\YOUR_SYMBOL_HERE\'
or insert the following function in your ~/.bashrc file, like so:
svncode() {
symbol=$1
[ $symbol ] && svn help status | grep \'$(echo $symbol)\' || \
echo "usage: svncode <symbol>"
}
Amazon Linux now supports python36.
python36-pip is not available. So need to follow a different route.
sudo yum install python36 python36-devel python36-libs python36-tools
# If you like to have pip3.6:
curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
The m000493
method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd
:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString());
changed to return builder3.ToString();
.
To allow Windows installers to find the installed Python directory in Windows 7, OR, change which Python installation to install an installer into, add the installed path into the InstallPath registry key's (Default) value:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.X\InstallPath
Where "X" is the Python version (that is, 2.5, 2.6, or 2.7).
To install a specific version of nodejs in Ubuntu you can use below commands, just specify and replace the version number, for example, node_12.x will fetch the latest of 12.
curl https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
sudo apt-add-repository "deb https://deb.nodesource.com/node_7.x $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install nodejs
As stated in the JQuery documentation
The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
Similar to John Wilkey's answer I would run python2 by finding which python
, something like using /usr/bin/python
and then creating an alias in .bash_profile
:
alias python2="/usr/bin/python"
I can now run python3 by calling python
and python2 by calling python2
.
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
See this complete explanation: http://book.mixu.net/node/ch5.html
You've got the right idea, so here's how to go ahead: the onclick
handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php
in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
For me small is beautiful so I'm using this technique:
In CSS file:
/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
#some-element { display: none; }
}
In jQuery/JavaScript file:
$( document ).ready(function() {
var is_mobile = false;
if( $('#some-element').css('display')=='none') {
is_mobile = true;
}
// now I can use is_mobile to run javascript conditionally
if (is_mobile == true) {
//Conditional script here
}
});
My objective was to have my site "mobile-friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.
For example, in my mobile version I don't want to activate the Facebook Like Box, because it loads all those profile images and stuff. And that's not good for mobile visitors. So, besides hiding the container element, I also do this inside the jQuery code block (above):
if(!is_mobile) {
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
You can see it in action at http://lisboaautentica.com
I'm still working on the the mobile version, so it's still not looking as it should, as of writing this.
Update by dekin88
There is a JavaScript API built-in for detecting media. Rather than using the above solution simply use the following:
$(function() {
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
if (isMobile) {
//Conditional script here
}
});
Browser Supports: http://caniuse.com/#feat=matchmedia
The advantage of this method is that it's not only simpler and shorter, but you can conditionally target different devices such as smartphones and tablets separately if necessary without having to add any dummy elements into the DOM.
The main difference from other solutions here is that this one reuses logic in RequiredAttribute
on the server side, and uses required
's validation method depends
property on the client side:
public class RequiredIf : RequiredAttribute, IClientValidatable
{
public string OtherProperty { get; private set; }
public object OtherPropertyValue { get; private set; }
public RequiredIf(string otherProperty, object otherPropertyValue)
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult($"Unknown property {OtherProperty}");
}
object otherValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (Equals(OtherPropertyValue, otherValue)) // if other property has the configured value
return base.IsValid(value, validationContext);
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "requiredif"; // data-val-requiredif
rule.ValidationParameters.Add("other", OtherProperty); // data-val-requiredif-other
rule.ValidationParameters.Add("otherval", OtherPropertyValue); // data-val-requiredif-otherval
yield return rule;
}
}
$.validator.unobtrusive.adapters.add("requiredif", ["other", "otherval"], function (options) {
var value = {
depends: function () {
var element = $(options.form).find(":input[name='" + options.params.other + "']")[0];
return element && $(element).val() == options.params.otherval;
}
}
options.rules["required"] = value;
options.messages["required"] = options.message;
});
For those that found the above solutions not working, it's because you may have a this
inside your class, which implies an extension method which, as the error message says, only makes sense on a non-generic static class. Your class isn't static. This doesn't seem to be something that makes sense as an extension method, since it's acting on the instance in question, so remove the this
.
I had this issue using Angular and SCSS. I had all my CSS nested so I decided to remove cursor: pointer;
out of it. And it worked.
Example:
.container{
.Approved{
color:green;
}
.ApprovedAndVerified{
color:black;
}
.lock_button{
font-size:35px;
display:block;
text-align:center;
}
}
.lock_button{
cursor:pointer;
}
This is how I did it. You don't need to delete Java 9 or newer version.
Step 1: Install Java 8
You can download Java 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Step 2: After installation of Java 8. Confirm installation of all versions.Type the following command in your terminal.
/usr/libexec/java_home -V
Step 3: Edit .bash_profile
sudo nano ~/.bash_profile
Step 4: Add 1.8 as default. (Add below line to bash_profile file).
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
Now Press CTRL+X to exit the bash. Press 'Y' to save changes.
Step 5: Reload bash_profile
source ~/.bash_profile
Step 6: Confirm current version of Java
java -version
To ensure that your build is completely rebuild, including checking the base image for updates, use the following options when building:
--no-cache
- This will force rebuilding of layers already available
--pull
- This will trigger a pull of the base image referenced using FROM ensuring you got the latest version.
The full command will therefore look like this:
docker build --pull --no-cache --tag myimage:version .
Same options are available for docker-compose:
docker-compose build --no-cache --pull
Note that if your docker-compose file references an image, the --pull option will not actually pull the image if there is one already.
To force docker-compose to re-pull this, you can run:
docker-compose pull
In Android, How to use a Cursor with a raw query in sqlite:
Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
"where Age > 10 LIMIT 5", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
c.close();
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
Setting setOnClickListener(null)
is a good idea to remove click listener at runtime.
And also someone commented that calling View.hasOnClickListeners()
after this will return true
, NO my friend.
Here is the implementation of hasOnClickListeners()
taken from android.view.View
class
public boolean hasOnClickListeners() {
ListenerInfo li = mListenerInfo;
return (li != null && li.mOnClickListener != null);
}
Thank GOD. It checks for null
.
So everything is safe. Enjoy :-)
This is what i did:
c1 = a1 - b1;
d1 = Math.Ceiling(c1 * 100) / 100;
subtracting two inputted numbers without rounding up or down the decimals. because the other solutions does not work for me. don't know if it will work for others, i just want to share this :) Hope it works tho for those who's finding solution to a problem similar to mine. Thanks
PS: i'm a beginner so feel free to point out something on this. :D this is good if you're actually dealing with money, cause of the cents right? it only have 2 decimal places and rounding it is a no no.
Following the instructions given by 'cfi' works for me, although there are a few pieces they left out that you might need:
1) Your lapack directory, after unzipping, may be called lapack-X-Y (some version number), so you can just rename that to LAPACK.
cd ~/src
mv lapack-[tab] LAPACK
2) In that directory, you may need to do:
cd ~/src/LAPACK
cp lapack_LINUX.a libflapack.a
I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.
When I execute cd ..
to the correct directory, I was able to commit, as expected.
You can do union
or simple list comprehension
[A.add(_) for _ in B]
A would have all the elements of B
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:
Dim comboSource As New Dictionary(Of String, String)()
cboMenu.Items.Clear()
For I = 0 To SomeList.GetUpperBound(0)
comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
Next I
cboMenu.DataSource = New BindingSource(comboSource, Nothing)
cboMenu.DisplayMember = "Value"
cboMenu.ValueMember = "Key"
Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:
Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
SetListGrid(cboManufMenu.SelectedValue)
End Sub
select * from table where column_date > now()- INTERVAL '6 hours';
You can use jQuery click
instead of using onclick
attribute, Try the following:
$('table').on('click', 'input[type="button"]', function(e){
$(this).closest('tr').remove()
})