I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:
Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error
To set this up correctly, there are 2 key files that need to be copied to the system:
com.google.android.maps.xml
com.google.android.maps.jar
These files are located in the any of these google app packs:
http://android.d3xt3...0120-signed.zip
http://goo-inside.me...0120-signed.zip
http://android.local...0120-signed.zip
These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1
After unzipping any of these files, you want to copy the files to your system, like-ah-so:
adb remount
adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions
adb push system/framework/com.google.android.maps.jar /system/framework
adb reboot
pip install --ignore-installed six
This will do the job, then you can try your first command.
I could never get the Windows 7 SDK to install either, and it suggested I remove the latest SDK and Visual Studio 2012 Express. That didn't work.
There was also something about .NET 3.5. I installed the Server 2008 SDK with .NET 3.5, uninstalled Visual Studio 2010 redistributables and made sure redistributables were unchecked in the installation options.
Also, you need the .NET 4 framework already installed, which you can download from Microsoft's site. Then it worked.
I run into this error when I tried to install Python 3.7.3 in Ubuntu 18.04 with next command: $ pyenv install 3.7.3
.
Installation succeeded after running $ sudo apt-get update && sudo apt-get install libffi-dev
(as suggested here).
The issue was solved there.
Run the next command:
adb kill-server
adb start-server
Is possible that drawn the next messages DeviceMonitor]Connection attempts: 1 DeviceMonitor]Connection attempts:2
For mysql8
and python 3.7
on windows, I find previous solutions seems not work for me.
Here is what worked for me:
pip install wheel
pip install mysqlclient-1.4.2-cp37-cp37m-win_amd64.whl
python -m pip install mysql-connector-python
python -m pip install SQLAlchemy
Reference: https://mysql.wisborg.dk/2019/03/03/using-sqlalchemy-with-mysql-8/
Install Visual Studio 2015 Community Edition from https://www.visualstudio.com, then
for Python 3.4
set VS100COMNTOOLS=%VS140COMNTOOLS% && pip install XX
You'll need to use DrawEllipse if you want to draw a circle using GDI+.
An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm
As others answers are correct, but too simple, so for completeness I'm presenting below code snippet to perform SELECT COUNT
on a sophisticated JPA Criteria query (with multiple joins, fetches, conditions).
It is slightly modified this answer.
public <T> long count(final CriteriaBuilder cb, final CriteriaQuery<T> selectQuery,
Root<T> root) {
CriteriaQuery<Long> query = createCountQuery(cb, selectQuery, root);
return this.entityManager.createQuery(query).getSingleResult();
}
private <T> CriteriaQuery<Long> createCountQuery(final CriteriaBuilder cb,
final CriteriaQuery<T> criteria, final Root<T> root) {
final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
final Root<T> countRoot = countQuery.from(criteria.getResultType());
doJoins(root.getJoins(), countRoot);
doJoinsOnFetches(root.getFetches(), countRoot);
countQuery.select(cb.count(countRoot));
countQuery.where(criteria.getRestriction());
countRoot.alias(root.getAlias());
return countQuery.distinct(criteria.isDistinct());
}
@SuppressWarnings("unchecked")
private void doJoinsOnFetches(Set<? extends Fetch<?, ?>> joins, Root<?> root) {
doJoins((Set<? extends Join<?, ?>>) joins, root);
}
private void doJoins(Set<? extends Join<?, ?>> joins, Root<?> root) {
for (Join<?, ?> join : joins) {
Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
joined.alias(join.getAlias());
doJoins(join.getJoins(), joined);
}
}
private void doJoins(Set<? extends Join<?, ?>> joins, Join<?, ?> root) {
for (Join<?, ?> join : joins) {
Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
joined.alias(join.getAlias());
doJoins(join.getJoins(), joined);
}
}
Hope it saves somebody's time.
Because IMHO JPA Criteria API is not intuitive nor quite readable.
I removed the tag in the .project .
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
It's worked very well for me.
Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.
For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.
If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.
If /foo/bar
is on NFS (or possibly some FUSE filesystem), that might be the problem.
Either way, adding -O
/ --omit-dir-times
to your command line will avoid it trying to set modification times on directories.
You have to follow the following sequence of opeartions:
Map
to MapSet
with map.entrySet();
Mapset.iterator();
Map.Entry
with iterator.next();
Entry.getKey()
and Entry.getValue()
# define Map
for (Map.Entry entry: map.entrySet)
System.out.println(entry.getKey() + entry.getValue);
It's a mechanism to invoke an API in an asynchrounous way. The sequence is the following
So you can invoke the api and tell your user the request is "processing" or "acquired" for example, and then update the status when you receive the response from the api.
Hope it makes sense. -G
Per your comments, to center all headings all you have to do is add text-align:center
to all of them at the same time, like so:
CSS
h1, h2, h3, h4, h5, h6 {
text-align: center;
}
in batch file abc.bat
cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3
I am assuming that your executible.exe
is present in c:\user\ben_dchost\documents\
I am also assuming that the parameters it takes are -flag1
-flag2
-flag3
Edited:
For the command you say you want to execute, do:
cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause
Hope this helps
That syntax isn't valid in Oracle. You can do this:
UPDATE table1 SET table1.value = (SELECT table2.CODE
FROM table2
WHERE table1.value = table2.DESC)
WHERE table1.UPDATETYPE='blah'
AND EXISTS (SELECT table2.CODE
FROM table2
WHERE table1.value = table2.DESC);
Or you might be able to do this:
UPDATE
(SELECT table1.value as OLD, table2.CODE as NEW
FROM table1
INNER JOIN table2
ON table1.value = table2.DESC
WHERE table1.UPDATETYPE='blah'
) t
SET t.OLD = t.NEW
It depends if the inline view is considered updateable by Oracle ( To be updatable for the second statement depends on some rules listed here ).
Simple excel file create in mvc 4
public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }
In Django, it acts as a configuration class and keeps the configuration data in one place!!
It is basically single window clearance system.You assign any work it will delegate to particular method in another class.
An enum is just another class in Java, it should be possible.
More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html
So yes, it should work.
Why not use a filter?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use
if(exists){
// it is in the dropdown
}
Or combine it:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:
# note that grep returns a list, so $matched needs to be in brackets to get the
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
print "found it: $matched\n";
}
If you need to match on a lot of different values, it might also be worth for you to consider putting the array
data into a hash
, since hashes allow you to do this efficiently without having to iterate through the list.
# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;
# check if the hash contains $match
if (defined $hash{$match}) {
print "found it\n";
}
I voted for Josh's answer, but would like to add one more to the list:
System.InvalidOperationException should be thrown if the argument is valid, but the object is in a state where the argument shouldn't be used.
Update Taken from MSDN:
InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.
Let's say that your object has a PerformAction(enmSomeAction action) method, valid enmSomeActions are Open and Close. If you call PerformAction(enmSomeAction.Open) twice in a row then the second call should throw the InvalidOperationException (since the arugment was valid, but not for the current state of the control)
Since you're already doing the right thing by programming defensively I have one other exception to mention is ObjectDisposedException. If your object implements IDisposable then you should always have a class variable tracking the disposed state; if your object has been disposed and a method gets called on it you should raise the ObjectDisposedException:
public void SomeMethod()
{
If (m_Disposed) {
throw new ObjectDisposedException("Object has been disposed")
}
// ... Normal execution code
}
Update: To answer your follow-up: It is a bit of an ambiguous situation, and is made a little more complicated by a generic (not in the .NET Generics sense) data type being used to represent a specific set of data; an enum or other strongly typed object would be a more ideal fit--but we don't always have that control.
I would personally lean towards the ArgumentOutOfRangeException and provide a message that indicates the valid values are 1-12. My reasoning is that when you talk about months, assuming all integer representations of months are valid, then you are expecting a value in the range of 1-12. If only certain months (like months that had 31 days) were valid then you would not be dealing with a Range per-se and I would throw a generic ArgumentException that indicated the valid values, and I would also document them in the method's comments.
The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like
initializeJSP(Experiment);
Add <br style="clear: both" />
after the last floated div worked for me.
OK, they all have got some similarities, they do the same things for you in different and similar ways, I divide them in 3 main groups as below:
webpack and browserify as popular ones, work like task runners but with more flexibility, aslo it will bundle everything together as your setting, so you can point to the result as bundle.js for example in one single file including the CSS and Javascript, for more details of each, look at the details below:
webpack
webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles - often only one - to be loaded by the browser.
It is incredibly configurable, but to get started you only need to understand Four Core Concepts: entry, output, loaders, and plugins.
This document is intended to give a high-level overview of these concepts, while providing links to detailed concept specific use-cases.
more here
browserify
Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.
more here
2) Task runners
gulp and grunt are task runners, basically what they do, creating tasks and run them whenever you want, for example you install a plugin to minify your CSS and then run it each time to do minifying, more details about each:
gulp
gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open source community at GitHub, used as a streaming build system in front-end web development. It is a task runner built on Node.js and Node Package Manager (npm), used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc. gulp uses a code-over-configuration approach to define its tasks and relies on its small, single-purposed plugins to carry them out. gulp ecosystem has 1000+ such plugins made available to choose from.
more here
grunt
Grunt is a JavaScript task runner, a tool used to automatically perform frequently used tasks such as minification, compilation, unit testing, linting, etc. It uses a command-line interface to run custom tasks defined in a file (known as a Gruntfile). Grunt was created by Ben Alman and is written in Node.js. It is distributed via npm. Presently, there are more than five thousand plugins available in the Grunt ecosystem.
more here
3) Package managers
package managers, what they do is managing plugins you need in your application and install them for you through github etc using package.json, very handy to update you modules, install them and sharing your app across, more details for each:
npm
npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public packages, called the npm registry. The registry is accessed via the client, and the available packages can be browsed and searched via the npm website.
more here
bower
Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. To get started, Bower works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you’re looking for. Bower keeps track of these packages in a manifest file, bower.json.
more here
and the most recent package manager that shouldn't be missed, it's young and fast in real work environment compare to npm which I was mostly using before, for reinstalling modules, it do double checks the node_modules folder to check the existence of the module, also seems installing the modules takes less time:
yarn
Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world. Yarn does this quickly, securely, and reliably so you don’t ever have to worry.
Yarn allows you to use other developers’ solutions to different problems, making it easier for you to develop your software. If you have problems, you can report issues or contribute back, and when the problem is fixed, you can use Yarn to keep it all up to date.
Code is shared through something called a package (sometimes referred to as a module). A package contains all the code being shared as well as a package.json file which describes the package.
more here
Try below code using RJSONIO in console
library(RJSONIO)
library(RCurl)
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")
json_file2 = RJSONIO::fromJSON(json_file)
head(json_file2)
Actually we get this error also when we create canvas in javascript as below.
document.createElement('canvas');
Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.
Thanks
line2 = "hello 12 hi 89"
temp1 = re.findall(r'\d+', line2) # through regular expression
res2 = list(map(int, temp1))
print(res2)
Hi ,
you can search all the integers in the string through digit by using findall expression .
In the second step create a list res2 and add the digits found in string to this list
hope this helps
Regards, Diwakar Sharma
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
Please note Craig McDaniel's solution is clearly better.
logging.Formatter's formatTime
method looks like this:
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
Notice the comma in "%s,%03d"
. This can not be fixed by specifying a datefmt
because ct
is a time.struct_time
and these objects do not record milliseconds.
If we change the definition of ct
to make it a datetime
object instead of a struct_time
, then (at least with modern versions of Python) we can call ct.strftime
and then we can use %f
to format microseconds:
import logging
import datetime as dt
class MyFormatter(logging.Formatter):
converter=dt.datetime.fromtimestamp
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = ct.strftime(datefmt)
else:
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = "%s,%03d" % (t, record.msecs)
return s
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
console.setFormatter(formatter)
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.
Or, to get milliseconds, change the comma to a decimal point, and omit the datefmt
argument:
class MyFormatter(logging.Formatter):
converter=dt.datetime.fromtimestamp
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = ct.strftime(datefmt)
else:
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = "%s.%03d" % (t, record.msecs)
return s
...
formatter = MyFormatter(fmt='%(asctime)s %(message)s')
...
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.
My solution:
.modal.in .modal-dialog
{
-webkit-transform: translate(0, calc(50vh - 50%));
-ms-transform: translate(0, 50vh) translate(0, -50%);
-o-transform: translate(0, calc(50vh - 50%));
transform: translate(0, 50vh) translate(0, -50%);
}
To change the directory for target dll/exe, use this in your pro file:
CONFIG(debug, debug|release) {
DESTDIR = build/debug
} else {
DESTDIR = build/release
}
You might also want to change directories for other build targets like object files and moc files (check qmake variable reference for details or qmake CONFIG() function reference).
The order of keys in an object wasn't guaranteed until ES2015. It was implementation-defined.
However, in ES2015 in was specified. Like many things in JavaScript, this was done for compatibility purposes and generally reflected an existing unofficial standard among most JS engines (with you-know-who being an exception).
The order is defined in the spec, under the abstract operation OrdinaryOwnPropertyKeys, which underpins all methods of iterating over an object's own keys. Paraphrased, the order is as follows:
All integer index keys (stuff like "1123"
, "55"
, etc) in ascending numeric order.
All string keys which are not integer indices, in order of creation (oldest-first).
All symbol keys, in order of creation (oldest-first).
It's silly to say that the order is unreliable - it is reliable, it's just probably not what you want, and modern browsers implement this order correctly.
Some exceptions include methods of enumerating inherited keys, such as the for .. in
loop. The for .. in
loop doesn't guarantee order according to the specification.
Here is an awesome and precise explanation I found.
TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.
TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.
TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.
TIMESTAMP is 4 bytes and DATETIME is 8 bytes.
TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'
Also...
It's mainly so you can make start and end statements clearer when creating HTML in loops:
<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
<? if (!$record['deleted']): ?>
<tr>
<? foreach ($display_fields as $field): ?>
<td><?= $record[$field] ?></td>
<? endforeach; ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action): ?>
<option value="<?= $action ?>"><?= $action ?>
<? endforeach; ?>
</td>
</tr>
<? else: ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? endif; ?>
<? endwhile; ?>
</table>
versus
<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
<? if (!$record['deleted']) { ?>
<tr>
<? foreach ($display_fields as $field) { ?>
<td><?= $record[$field] ?></td>
<? } ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action) { ?>
<option value="<?= $action ?>"><?= action ?>
<? } ?>
</td>
</tr>
<? } else { ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? } ?>
<? } ?>
</table>
Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach
) form can make things easier for your brain to parse. With the normal style, the closing }
can be left on their own and make it hard to tell what they're actually closing.
DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);
Step by step
DECLARE @min INT = 3;
DECLARE @max INT = 6;
DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk;
SELECT @result;
Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.
CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT RAND() AS seed
and then create the random function
CREATE FUNCTION udf_RandomNumberBetween
(
@min INT,
@max INT
)
RETURNS INT
AS
BEGIN
RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END
I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).
app.py
:
from flask import Flask
from celery import Celery
broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue
app = Flask(__name__)
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py
@celery.task(bind=True)
def some_long_task(self, x, y):
# Do some long task
...
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
data = json.loads(request.data)
text_list = data.get('text_list')
final_file = audio_class.render_audio(data=text_list)
some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables
return Response(
mimetype='application/json',
status=200
)
Run your Flask app, and start another process to run your celery worker.
$ celery worker -A app.celery --loglevel=debug
I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.
$('input[type="radio"]').change(function(){
if($("input[name='group']:checked")){
$(div).show();
}
});
The idea of your first snippet is right. You probably meant to check iByteCount == -1
: whether the file has at least one byte:
if (iByteCount == -1)
System.out.println("NO ERRORS!");
else
System.out.println("SOME ERRORS!");
You can always refresh the user's access token every time the user logs into your site through facebook. The offline access can't guarantee you get a life-long time access token, the access token changes whenever the user revoke you application access or the user changes his/her password.
Quoted from facebook http://developers.facebook.com/docs/authentication/
Note: If the application has not requested offline_access permission, the access token is time-bounded. Time-bounded access token also get invalidated when the user logs out of Facebook. If the application has obtained offline_access permission from the user, the access token does not have an expiry. However it gets invalidated whenever the user changes his/her password.
Assume you store the user's facebook uid and access token in a users table in your database,every time the user clicks on the "Login with facebook" button, you check the login statususing facebook Javascript API, and then examine the connection status from the response,if the user has connected to your site, you can then update the access token in the table.
You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)
Example:
elevator=deadline
This will make "deadline" the default I/O scheduler for all block devices.
If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.
https://github.com/kata198/ioschedset
If you're on Archlinux it's available in aur:
https://aur.archlinux.org/packages/ioschedset
Some example usage:
# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda: bfq
sr0: bfq
# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none
# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...
[sudo] password for username:
+ Successfully set sda to 'kyber'!
# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda: kyber
sr0: bfq
# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...
+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!
# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda: mq-deadline
Usage should be self-explanatory. The tools are standalone and only require bash.
Hope this helps!
EDIT: Disclaimer, these are scripts I wrote.
git push --delete origin $TAGNAME
is the correct approach (in addition of a local delete).
But: make sure to use Git 2.31.
"git push $there --delete
"(man) should have been diagnosed as an error, but instead turned into a matching push, which has been corrected with Git 2.31 (Q1 2021).
See commit 20e4164 (23 Feb 2021) by Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit 1400458, 25 Feb 2021)
push
: do not turn --delete '' into a matching pushNoticed-by: Tilman Vogel
When we added a syntax sugar "
git push remote --delete
"(man)<ref>
to "git push
"(man) as a synonym to the canonicalgit push remote
(man) : syntax at f517f1f ("builtin-push
:add
(man)--delete
as syntactic sugar for :foo", 2009-12-30, Git v1.7.0-rc0 -- merge), we weren't careful enough to make sure that<ref>
is not empty.Blindly rewriting "--delete " to ":" means that an empty string
<ref>
results in refspec ":", which is the syntax to ask for "matching" push that does not delete anything.Worse yet, if there were matching refs that can be fast-forwarded, they would have been published prematurely, even if the user feels that they are not ready yet to be pushed out, which would be a real disaster.
For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.
What are you loading the files for - configuration or data (like an input file) or as a resource?
BufferedReader file = new BufferedReader(new FileReader(filename))
and then read each line of the file using file.readLine();
Don't forget to close the file.I have used this one and it served the purpose:
if($date < date("Y-m-d") ) {
echo "Date is in the past";}
BR
To sum up, the quick linkedlist method:
List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);
The window
binding refers to a built-in object provided by the browser. It represents the browser window that contains the document
. Calling its addEventListener
method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
window
or document
but
some events like resize
, and other events related to loading
,
unloading
, and opening/closing
should all be set on the window.For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:
Using Windows Explorer, navigate to:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013
In that folder, you'll see a shortcut named Visual Studio Tools
that maps to (assuming default installation):
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts
Double-click the shortcut (or go to the folder above).
From that folder, copy the shortcut named Developer Command Prompt for VS2013
(and any others you find useful) to the first directory (for the Start Menu
). You'll likely be prompted for administrative access (do so).
Once you've done that, you'll now have an icon available for the 2013 command prompt.
I wanted to share a library I've built for this. It's a tiny library, but a big improvement (IMHO) over .settings files.
The library is called Jot (GitHub). Here is an old The Code Project article I wrote about it.
Here's how you'd use it to keep track of a window's size and location:
public MainWindow()
{
InitializeComponent();
_stateTracker.Configure(this)
.IdentifyAs("MyMainWindow")
.AddProperties(nameof(Height), nameof(Width), nameof(Left), nameof(Top), nameof(WindowState))
.RegisterPersistTrigger(nameof(Closed))
.Apply();
}
The benefit compared to .settings files: There's considerably less code, and it's a lot less error-prone since you only need to mention each property once.
With a settings files you need to mention each property five times: once when you explicitly create the property and an additional four times in the code that copies the values back and forth.
Storage, serialization, etc. are completely configurable. When the target objects are created by an IoC container, you can [hook it up][] so that it applies tracking automatically to all objects it resolves, so that all you need to do to make a property persistent is slap a [Trackable] attribute on it.
It's highly configurable, and you can configure: - when data is persisted and applied globally or for each tracked object - how it's serialized - where it's stored (e.g. file, database, online, isolated storage, registry) - rules that can cancel applying/persisting data for a property
Trust me, the library is top notch!
If the error happens with error column "File" as SGEN, then the fix needs to be in a file sgen.exe.config
, next to sgen.exe
. For example, for VS 2015, create C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sgen.exe.config
. Minimum file contents: <configuration><startup useLegacyV2RuntimeActivationPolicy="true"/></configuration>
Source: SGEN Mixed mode assembly
I search three places as shown below. Comments welcome.
public URL getResource(String resource){
URL url ;
//Try with the Thread Context Loader.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader != null){
url = classLoader.getResource(resource);
if(url != null){
return url;
}
}
//Let's now try with the classloader that loaded this class.
classLoader = Loader.class.getClassLoader();
if(classLoader != null){
url = classLoader.getResource(resource);
if(url != null){
return url;
}
}
//Last ditch attempt. Get the resource from the classpath.
return ClassLoader.getSystemResource(resource);
}
v1
, v2
.v3
.v4
first = [1, 2, 3, 1]
second = [4, 5, 6]
output: [5, 7, 9, 1]
If you have an unknown number of lists of the same length, you can use the function v5
.
v6
- The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y)
is equivalent to the expression x+y
.
v7
- Assuming both lists first
and second
have same length, you do not need zip or anything else.
################
first = [1, 2, 3]
second = [4, 5, 6]
####### v1 ########
third1 = [sum(i) for i in zip(first,second)]
####### v2 ########
third2 = [x + y for x, y in zip(first, second)]
####### v3 ########
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
third3 = [sum(x) for x in zip(*lists_of_lists)]
####### v4 ########
from itertools import zip_longest
third4 = list(map(sum, zip_longest(first, second, fillvalue=0)))
####### v5 ########
def sum_lists(*args):
return list(map(sum, zip(*args)))
third5 = sum_lists(first, second)
####### v6 ########
import operator
third6 = list(map(operator.add, first,second))
####### v7 ########
third7 =[first[i]+second[i] for i in range(len(first))]
####### v(i) ########
print(third1) # [5, 7, 9]
print(third2) # [5, 7, 9]
print(third3) # [5, 7, 9]
print(third4) # [5, 7, 9]
print(third5) # [5, 7, 9]
print(third6) # [5, 7, 9]
print(third7) # [5, 7, 9]
I wrote this simple code that is testing localStorage size in bytes.
https://github.com/gkucmierz/Test-of-localStorage-limits-quota
const check = bytes => {
try {
localStorage.clear();
localStorage.setItem('a', '0'.repeat(bytes));
localStorage.clear();
return true;
} catch(e) {
localStorage.clear();
return false;
}
};
Github pages:
https://gkucmierz.github.io/Test-of-localStorage-limits-quota/
I have the same results on desktop chrome, opera, firefox, brave and mobile chrome which is ~5Mbytes
And half smaller result in safari ~2Mbytes
int
is a primitive data type while Integer
is a Reference or Wrapper Type (Class) in Java.
after java 1.5
which introduce the concept of autoboxing and unboxing you can initialize both int
or Integer
like this.
int a= 9
Integer a = 9 // both valid After Java 1.5.
why
Integer.parseInt("1");
but notint.parseInt("1");
??
Integer
is a Class defined in jdk
library and parseInt()
is a static method belongs to Integer
Class
So, Integer.parseInt("1");
is possible in java. but int
is primitive type (assume like a keyword) in java. So, you can't call parseInt()
with int
.
getElementById
is defined by DOM Level 1 HTML to return null
in the case no element is matched.
!==null
is the most explicit form of the check, and probably the best, but there is no non-null
falsy value that getElementById
can return - you can only get null
or an always-truthy Element object. So there's no practical difference here between !==null
, !=null
or the looser if (document.getElementById('xx'))
.
i think that the simple way in oracle is this:
SELECT Salary FROM
(SELECT DISTINCT Salary FROM Employee ORDER BY Salary desc)
WHERE ROWNUM <= 2;
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
You should also click on "Install Charles CA SSL Certificates.." from the Charles Help menu. See more detailed instructions at http://blog.noodlewerk.com/general/tutorial-using-charles-proxy-to-debug-https-communication-between-server-and-ios-apps/
if ($inputs['type'] == 'attach') {
The code is valid, but it expects the function parameter $inputs
to be an array. The "Illegal string offset" warning when using $inputs['type']
means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type'
is not suitable.)
So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.
However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type'
to 0
, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)
You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs);
in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:
if (is_array($inputs) && $inputs['type'] == 'attach') {
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".
To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P
So maybe:
def super_cool_logic():
# execute common code here
@app.route("/foo")
def do_foo():
# do some logic here
super_cool_logic()
return render_template("foo.html")
@app.route("/baz")
def do_baz():
if some_condition:
return render_template("baz.html")
else:
super_cool_logic()
return render_template("foo.html", messages={"main":"Condition failed on page baz"})
I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)
I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.
You can use it like this:
In Mvc:
@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});
In Html:
<input type="text" name="Id" data_val_number="10"/>
1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame is empty or not then try this code. 2) when this situation can happen? This situation happens when a single function is used to plot more than one DataFrame which are passed as parameter.In such a situation the function try to plot the data even when a DataFrame is empty and thus plot an empty figure!. It will make sense if simply display 'DataFrame has no data' message. 3) why? if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values is considered non empty) then it is desirable not to plot but put out a message : Suppose we have two DataFrames df1 and df2. The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message if a DataFrame is empty(instead of plotting):
df1 df2
col1 col2 col1 col2
Nan 2 Nan Nan
2 Nan Nan Nan
and the function:
def myfunc(df):
if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
print('not empty')
df.plot(kind='barh')
else:
display a message instead of plotting if it is empty
print('empty')
This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:
from django.test import Client
from django.core.urlresolvers import reverse
#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4))
Actually the orderBy
filter can take as a parameter not only a string but also a function. From the orderBy
documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
The other thing worth noting is that orderBy
is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy
should be enough for most uses cases).
Yes I think this would be quicker.
Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1
find . -type d -exec sh -c "echo -n {}; echo -n ' x '; echo {}" \;
You can use a char, or another small number container for it.
Pseudo-code
#define TRUE 1
#define FALSE 0
char bValue = TRUE;
I think that application should be kill in some case. For example, there is an app can be used only after login. The login activity has two buttons, 'login' and 'cancel'. When you click 'cancel' button, it definitely means 'Terminate the app'. Nobody wants the app alive in the background. So I agree that some cases need to shut down the app.
You could just inline a generator to filter out the null values if you want to pretend they don't exist. Of course this is assuming the null bytes are not really part of the encoding and really are some kind of erroneous artifact or bug.
with open(filepath, "rb") as f:
reader = csv.reader( (line.replace('\0','') for line in f) )
try:
for row in reader:
print 'Row read successfully!', row
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
This worked for me instead of startsWith
: Build.FINGERPRINT.contains("generic")
For more check this link: https://gist.github.com/espinchi/168abf054425893d86d1
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
I have this in my .gitconfig file. It is still a draft, but proved useful as of now. It helps me to always reattach the submodules to their branch.
[alias]
######################
#
#Submodules aliases
#
######################
#git sm-trackbranch : places all submodules on their respective branch specified in .gitmodules
#This works if submodules are configured to track a branch, i.e if .gitmodules looks like :
#[submodule "my-submodule"]
# path = my-submodule
# url = [email protected]/my-submodule.git
# branch = my-branch
sm-trackbranch = "! git submodule foreach -q --recursive 'branch=\"$(git config -f $toplevel/.gitmodules submodule.$name.branch)\"; git checkout $branch'"
#sm-pullrebase :
# - pull --rebase on the master repo
# - sm-trackbranch on every submodule
# - pull --rebase on each submodule
#
# Important note :
#- have a clean master repo and subrepos before doing this !
#- this is *not* equivalent to getting the last committed
# master repo + its submodules: if some submodules are tracking branches
# that have evolved since the last commit in the master repo,
# they will be using those more recent commits !
#
# (Note : On the contrary, git submodule update will stick
#to the last committed SHA1 in the master repo)
#
sm-pullrebase = "! git pull --rebase; git submodule update; git sm-trackbranch ; git submodule foreach 'git pull --rebase' "
# git sm-diff will diff the master repo *and* its submodules
sm-diff = "! git diff && git submodule foreach 'git diff' "
#git sm-push will ask to push also submodules
sm-push = push --recurse-submodules=on-demand
#git alias : list all aliases
#useful in order to learn git syntax
alias = "!git config -l | grep alias | cut -c 7-"
Just tried the stored procedure script. Seems the problem is the '
marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.
So you want:
delimiter //
Instead of:
delimiter '//'
Works for me :)
As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you can change the parent shell directory on Unix with this horrible hack:
def quote_against_shell_expansion(s):
import pipes
return pipes.quote(s)
def put_text_back_into_terminal_input_buffer(text):
# use of this means that it only works in an interactive session
# (and if the user types while it runs they could insert characters between the characters in 'text'!)
import fcntl, termios
for c in text:
fcntl.ioctl(1, termios.TIOCSTI, c)
def change_parent_process_directory(dest):
# the horror
put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.A simple js solution to set modal height proportional to body's height :
$(document).ready(function () {
$('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});
body's height has to be 100% :
html, body {
height: 100%;
min-height: 100%;
}
I set modal body height to 80% of body, this can be of course customized.
Hope it helps.
I ran into similar situation where I had to merge Date and Time fields to DateTime field. None of the above mentioned solution work, specially adding two fields as the data type for addition of these 2 fields is not same.
I created below solution, where I added hour and then minute part to the date. This worked beautifully for me. Please check it out and do let me know if you get into any issues.
;with tbl as ( select StatusTime = '12/30/1899 5:17:00 PM', StatusDate = '7/24/2019 12:00:00 AM' ) select DATEADD(MI, DATEPART(MINUTE,CAST(tbl.StatusTime AS TIME)),DATEADD(HH, DATEPART(HOUR,CAST(tbl.StatusTime AS TIME)), CAST(tbl.StatusDate as DATETIME))) from tbl
Result: 2019-07-24 17:17:00.000
You still need to worry about memory when you are writing managed code unless your application is trivial. I will suggest two things: first, read CLR via C# because it will help you understand memory management in .NET. Second, learn to use a tool like CLRProfiler (Microsoft). This can give you an idea of what is causing your memory leak (e.g. you can take a look at your large object heap fragmentation)
You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.
Try using the exact, or absolute, path.
You can try below code. it’s very easy method for push new fragment from old fragment.
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private final static String TAG = "DashBoardActivity";
public void replaceFragment(Fragment fragment, String TAG) {
try {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commitAllowingStateLoss();
} catch (Exception e) {
// TODO: handle exception
}
}
Here's my solution:
def un_camel(text):
""" Converts a CamelCase name into an under_score name.
>>> un_camel('CamelCase')
'camel_case'
>>> un_camel('getHTTPResponseCode')
'get_http_response_code'
"""
result = []
pos = 0
while pos < len(text):
if text[pos].isupper():
if pos-1 > 0 and text[pos-1].islower() or pos-1 > 0 and \
pos+1 < len(text) and text[pos+1].islower():
result.append("_%s" % text[pos].lower())
else:
result.append(text[pos].lower())
else:
result.append(text[pos])
pos += 1
return "".join(result)
It supports those corner cases discussed in the comments. For instance, it'll convert getHTTPResponseCode
to get_http_response_code
like it should.
Assuming staff_id + date form a uk, this is another method:
SELECT STAFF_ID, SITE_ID, PAY_LEVEL
FROM TABLE t
WHERE END_ENROLLMENT_DATE is null
AND DATE = (SELECT MAX(DATE)
FROM TABLE
WHERE staff_id = t.staff_id
AND DATE <= SYSDATE)
You can use
hdfs fsck /
to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with
hdfs fsck / | egrep -v '^\.+$' | grep -v eplica
which ignores lines with nothing but dots and lines talking about replication.
Once you find a file that is corrupt
hdfs fsck /path/to/corrupt/file -locations -blocks -files
Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.
You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.
Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.
Once you determine what happened and you cannot recover any more blocks, just use the
hdfs fs -rm /path/to/file/with/permanently/missing/blocks
command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.
You can use the lastval()
function:
Return value most recently obtained with
nextval
for any sequence
So something like this:
INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val) VALUES (lastval());
This will work fine as long as no one calls nextval()
on any other sequence (in the current session) between your INSERTs.
As Denis noted below and I warned about above, using lastval()
can get you into trouble if another sequence is accessed using nextval()
between your INSERTs. This could happen if there was an INSERT trigger on Table1
that manually called nextval()
on a sequence or, more likely, did an INSERT on a table with a SERIAL
or BIGSERIAL
primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could use currval()
but you'd need to know the name of the relevant sequence:
INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val) VALUES (currval('Table1_id_seq'::regclass));
The automatically generated sequence is usually named t_c_seq
where t
is the table name and c
is the column name but you can always find out by going into psql
and saying:
=> \d table_name;
and then looking at the default value for the column in question, for example:
id | integer | not null default nextval('people_id_seq'::regclass)
FYI: lastval()
is, more or less, the PostgreSQL version of MySQL's LAST_INSERT_ID
. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linking lastval()
to something familiar might clarify things.
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
In java you can use setFetchSource like this :
client.prepareSearch(index).setTypes(type)
.setFetchSource(new String[] { "field1", "field2" }, null)
import com.google.common.collect.Lists;
import java.util.List;
/**
* @author Ciccotta Andrea on 06/11/2020.
*/
public class CollectionUtils {
/**
* It models the prepend O(1), used against the common append/add O(n)
* @param head first element of the list
* @param body rest of the elements of the list
* @return new list (with different memory-reference) made by [head, ...body]
*/
public static <E> List<Object> prepend(final E head, List<E> final body){
return Lists.asList(head, body.toArray());
}
/**
* it models the typed version of prepend(E head, List<E> body)
* @param type the array into which the elements of this list are to be stored
*/
public static <E> List<E> prepend(final E head, List<E> body, final E[] type){
return Lists.asList(head, body.toArray(type));
}
}
You can use "smart BASIC" programming language. It is a genuine but very advanced BASIC language with all its power and simplicity. Using its free SDK, BASIC code can be easily published as a standalone App Store application. There are many apps in App Store, written in "smart BASIC" programming language.
Introducing a new method signature that changes the parameter types is called overloading:
public boolean equals(People other){
Here People
is different than Object
.
When a method signature remains the identical to that of its superclass, it is called overriding and the @Override
annotation helps distinguish the two at compile-time:
@Override
public boolean equals(Object other){
Without seeing the actual declaration of age
, it is difficult to say why the error appears.
I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:
Now your column headers should repeat on each page.
It is supported as of Java 12. Check out JEP 354. No "range" possibilities here, but can be useful either.
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);//number of letters
case TUESDAY -> System.out.println(7);
case THURSDAY, SATURDAY -> System.out.println(8);
case WEDNESDAY -> System.out.println(9);
}
You should be able to implement that on ints too. Note through that your switch statement have to be exhaustive (using default
keyword, or using all possible values in case statements).
Even cleaner would be to just put p#given img { float: right }
in the style sheet, or in the <head>
and wrapped in style
tags. Then, just use the markdown ![Alt text](/path/to/img.jpg)
.
Writing from phone, but curvycorners is really good, since it adds it's own borders only if browser doesn't support it by default. In other words, browsers which already support some CSS3 will use their own system to provide corners.
https://code.google.com/p/curvycorners/
Switch to Branch2
git checkout Branch2
Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:
git rebase Branch1
Which would leave you with the desired result in Branch2:
a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
You can delete Branch1.
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Read this doc which will explain to you what to do.
https://devcenter.heroku.com/articles/buildpacks
Setting a buildpack on an application
You can change the buildpack used by an application by setting the buildpack value.
When the application is next pushed, the new buildpack will be used.$ heroku buildpacks:set heroku/php
Buildpack set. Next release on random-app-1234 will use heroku/php.
Rungit push heroku master
to create a new release using this buildpack.
This is whay its not working for you since you did not set it up.
... When the application is next pushed, the new buildpack will be used.
You may also specify a buildpack during app creation
:
$ heroku create myapp --buildpack heroku/python
CSS only solution for modern browsers
@keyframes slidein {
0% {margin-left:1500px;}
100% {margin-left:0px;}
}
.note {
animation-name: slidein;
animation-duration: .9s;
display: block;
}
I have noticed 3 mistakes can can give rise to the same error:
If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.
$list= (new LeaveApplication())
->whereDate('from','<=', $today)
->whereDate('to','>=', $today)
->get();
I have a workaround if you need to clone or pull and the problem lies in the size of the repository history. It may also help when you want to push later, with no guarantee.
Simply retrieve the last commits with --depth=[number of last commits]
.
You can do this at clone time, or, if working from a local repository to which you added a remote, at pull time. For instance, to only retrieve the last commit (of each branch):
git clone repo --depth=1
# or
git pull --depth=1
UPDATE: if the remote is getting too much ahead of you, the issue may come back later as you try to pull the last changes, but there are too many and the connection closes with curl 56. You may have to git pull --depth=[number of commits ahead on remote]
, which is tedious if you're working on a very active repository.
You can use varargs
public function yourFunction(Parameter... parameters)
See also
Give this a try:
.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
background-color: #color;
}
Setting the image using picture.ImageLocation()
works fine, but you are using a relative path. Check your path against the location of the .exe
after it is built.
For example, if your .exe
is located at:
<project folder>/bin/Debug/app.exe
The image would have to be at:
<project folder>/bin/Image/1.jpg
Of course, you could just set the image at design-time (the Image
property on the PictureBox
property sheet).
If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image
. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory
to Copy if newer
.
At this point the image file will be copied when you build the application and you can use
picture.ImageLocation = @"Image\1.jpg";
a simple hack with the first answer
var getLocation = function(href=window.location.href) {
var l = document.createElement("a");
l.href = href;
return l;
};
this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname
To get a negative version of a number in JavaScript you can always use the ~
bitwise operator.
For example, if you have a = 1000
and you need to convert it to a negative, you could do the following:
a = ~a + 1;
Which would result in a
being -1000
.
To style the Toolbar on Android 21+ it's a bit different.
<style name="DarkTheme.v21" parent="DarkTheme.v19">
<!-- toolbar background color -->
<item name="android:navigationBarColor">@color/color_primary_blue_dark</item>
<!-- toolbar back button color -->
<item name="toolbarNavigationButtonStyle">@style/Toolbar.Button.Navigation.Tinted</item>
</style>
<style name="Toolbar.Button.Navigation.Tinted" parent="Widget.AppCompat.Toolbar.Button.Navigation">
<item name="tint">@color/color_white</item>
</style>
You probably want to have a list of supported encodings. For each file, try each encoding in turn, maybe starting with UTF-8. Every time you catch the MalformedInputException
, try the next encoding.
The quoting rules are painful. I think you want:
SELECT nextval('foo."SQ_ID"');
to prevent case-folding of SQ_ID
.
TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free
pysc: Service Control Manager on Python
Example script to run as a service taken from pythonhosted.org:
from xmlrpc.server import SimpleXMLRPCServer from pysc import event_stop class TestServer: def echo(self, msg): return msg if __name__ == '__main__': server = SimpleXMLRPCServer(('127.0.0.1', 9001)) @event_stop def stop(): server.server_close() server.register_instance(TestServer()) server.serve_forever()
Create and start service
import os import sys from xmlrpc.client import ServerProxy import pysc if __name__ == '__main__': service_name = 'test_xmlrpc_server' script_path = os.path.join( os.path.dirname(__file__), 'xmlrpc_server.py' ) pysc.create( service_name=service_name, cmd=[sys.executable, script_path] ) pysc.start(service_name) client = ServerProxy('http://127.0.0.1:9001') print(client.echo('test scm'))
Stop and delete service
import pysc service_name = 'test_xmlrpc_server' pysc.stop(service_name) pysc.delete(service_name)
pip install pysc
Here's my solution..
Concept_Behind::
push(struct Stack* S,int data)
::This function enqueue first element in Q1 and rest in Q2
pop(struct Stack* S)
::if Q2 is not empty the transfers all elem's into Q1 and return the last elem in Q2
else(which means Q2 is empty ) transfers all elem's into Q2 and returns the last elem in Q1
Efficiency_Behind::
push(struct Stack*S,int data)
::O(1)//since single enqueue per data
pop(struct Stack* S)
::O(n)//since tranfers worst n-1 data per pop.
#include<stdio.h>
#include<stdlib.h>
struct Queue{
int front;
int rear;
int *arr;
int size;
};
struct Stack {
struct Queue *Q1;
struct Queue *Q2;
};
struct Queue* Qconstructor(int capacity)
{
struct Queue *Q=malloc(sizeof(struct Queue));
Q->front=Q->rear=-1;
Q->size=capacity;
Q->arr=malloc(Q->size*sizeof(int));
return Q;
}
int isEmptyQueue(struct Queue *Q)
{
return (Q->front==-1);
}
int isFullQueue(struct Queue *Q)
{
return ((Q->rear+1) % Q->size ==Q->front);
}
void enqueue(struct Queue *Q,int data)
{
if(isFullQueue(Q))
{
printf("Queue overflow\n");
return;}
Q->rear=Q->rear+1 % Q->size;
Q->arr[Q->rear]=data;
if(Q->front==-1)
Q->front=Q->rear;
}
int dequeue(struct Queue *Q)
{
if(isEmptyQueue(Q)){
printf("Queue underflow\n");
return;
}
int data=Q->arr[Q->front];
if(Q->front==Q->rear)
Q->front=-1;
else
Q->front=Q->front+1 % Q->size;
return data;
}
///////////////////////*************main algo****************////////////////////////
struct Stack* Sconstructor(int capacity)
{
struct Stack *S=malloc(sizeof(struct Stack));
S->Q1=Qconstructor(capacity);
S->Q2=Qconstructor(capacity);
return S;
}
void push(struct Stack *S,int data)
{
if(isEmptyQueue(S->Q1))
enqueue(S->Q1,data);
else
enqueue(S->Q2,data);
}
int pop(struct Stack *S)
{
int i,tmp;
if(!isEmptyQueue(S->Q2)){
for(i=S->Q2->front;i<=S->Q2->rear;i++){
tmp=dequeue(S->Q2);
if(isEmptyQueue(S->Q2))
return tmp;
else
enqueue(S->Q1,tmp);
}
}
else{
for(i=S->Q1->front;i<=S->Q1->rear;i++){
tmp=dequeue(S->Q1);
if(isEmptyQueue(S->Q1))
return tmp;
else
enqueue(S->Q2,tmp);
}
}
}
////////////////*************end of main algo my algo************
///////////////*************push() O(1);;;;pop() O(n);;;;*******/////
main()
{
int size;
printf("Enter the number of elements in the Stack(made of 2 queue's)::\n");
scanf("%d",&size);
struct Stack *S=Sconstructor(size);
push(S,1);
push(S,2);
push(S,3);
push(S,4);
printf("%d\n",pop(S));
push(S,5);
printf("%d\n",pop(S));
printf("%d\n",pop(S));
printf("%d\n",pop(S));
printf("%d\n",pop(S));
}
Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.
In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64
equivalent of the int
input. float32
datatype is also available in GoLang
Code:
package main
import "fmt"
func main() {
var i int
fmt.Println("Enter an Integer input: ")
fmt.Scanf("%d", &i)
f := float64(i)
fmt.Printf("The float64 representation of %d is %f\n", i, f)
}
Solution:
>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000
This article seems to offer a pretty good overview of the difference.
From the page:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to “image”, but the BUTTON element type allows content.
The Button Element - W3C
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
List<T>
has a FindAll
method that will do the filtering for you and return a subset of the list.
MSDN has a great code example here: http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx
EDIT: I wrote this before I had a good understanding of LINQ and the Where()
method. If I were to write this today i would probably use the method Jorge mentions above. The FindAll
method still works if you're stuck in a .NET 2.0 environment though.
The new C++11 style:
#include <algorithm>
#include <string>
#include <cctype>
/// Try to find in the Haystack the Needle - ignore case
bool findStringIC(const std::string & strHaystack, const std::string & strNeedle)
{
auto it = std::search(
strHaystack.begin(), strHaystack.end(),
strNeedle.begin(), strNeedle.end(),
[](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
);
return (it != strHaystack.end() );
}
Explanation of the std::search can be found on cplusplus.com.
YourJPanelForm stuff = new YourJPanelForm();
JOptionPane.showMessageDialog(null,stuff,"Your title here bro",JOptionPane.PLAIN_MESSAGE);
Your modal dialog awaits...
If your SQL doesn't support NULLS FIRST
or NULLS LAST
, the simplest way to do this is to use the value IS NULL
expression:
ORDER BY Next_Contact_Date IS NULL, Next_Contact_Date
to put the nulls at the end (NULLS LAST
) or
ORDER BY Next_Contact_Date IS NOT NULL, Next_Contact_Date
to put the nulls at the front. This doesn't require knowing the type of the column and is easier to read than the CASE
expression.
EDIT: Alas, while this works in other SQL implementations like PostgreSQL and MySQL, it doesn't work in MS SQL Server. I didn't have a SQL Server to test against and relied on Microsoft's documentation and testing with other SQL implementations. According to Microsoft, value IS NULL
is an expression that should be usable just like any other expression. And ORDER BY
is supposed to take expressions just like any other statement that takes an expression. But it doesn't actually work.
The best solution for SQL Server therefore appears to be the CASE
expression.
Given an email address like...
[email protected]
The length limits are as follows:
256
characters maximum.64
character maximum.254
characters maximum.SMTP originally defined what a path was in RFC821, published August 1982, which is an official Internet Standard (most RFC's are only proposals). To quote it...
...a reverse-path, specifies who the mail is from.
...a forward-path, which specifies who the mail is to.
RFC2821, published in April 2001, is the Obsoleted Standard that defined our present maximum values for local-parts, domains, and paths. A new Draft Standard, RFC5321, published in October 2008, keeps the same limits. In between these two dates, RFC3696 was published, on February 2004. It mistakenly cites the maximum email address limit as 320
-characters, but this document is "Informational" only, and states: "This memo provides information for the Internet community. It does not specify an Internet standard of any kind." So, we can disregard it.
To quote RFC2821, the modern, accepted standard as confirmed in RFC5321...
4.5.3.1.1. Local-part
The maximum total length of a user name or other local-part is 64 characters.
4.5.3.1.2. Domain
The maximum total length of a domain name or number is 255 characters.
4.5.3.1.3. Path
The maximum total length of a reverse-path or forward-path is 256 characters (including the punctuation and element separators).
You'll notice that I indicate a domain maximum of 254 and the RFC indicates a domain maximum of 255. It's a matter of simple arithmetic. A 255-character domain, plus the "@" sign, is a 256-character path, which is the max path length. An empty or blank name is invalid, though, so the domain actually has a maximum of 254.
The default value for client_max_body_size
directive is 1 MiB.
It can be set in http
, server
and location
context — as in the most cases,
this directive in a nested block takes precedence over the same directive in the ancestors blocks.
Excerpt from the ngx_http_core_module documentation:
Syntax: client_max_body_size size; Default: client_max_body_size 1m; Context: http, server, location
Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.
Don't forget to reload configuration
by nginx -s reload
or service nginx reload
commands prepending with sudo
(if any).
Something likes this
public void testPrintOut() {
int val1 = 8;
String val2 = "$951.23";
String val3 = "$215.92";
String val4 = "$198,301.22";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
val1 = 9;
val2 = "$950.19";
val3 = "$216.95";
val4 = "$198,084.26";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}
Since y is an iterable I really do not see why the calls to append:
a = np.array(list(y))
will do and it's much faster:
import timeit
print timeit.timeit('list(s)', 's=set(x for x in xrange(1000))')
# 23.952975494633154
print timeit.timeit("""li=[]
for x in s: li.append(x)""", 's=set(x for x in xrange(1000))')
# 189.3826994248866
Python has support for CSV files in the eponymous csv
module. It is relatively misnamed since it support much more that just comma separated values.
If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values...
Using the =~
operator:
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor
Here is a way to update by an index much like foo[x] = 9
where x
is a key and 9 is the value
var views = new Dictionary<string, bool>();
foreach (var g in grantMasks)
{
string m = g.ToString();
for (int i = 0; i <= m.Length; i++)
{
views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
}
}
It can be done with excellent py-spy. It's a sampling profiler for Python programs, so its job is to attach to a Python processes and sample their call stacks. Hence, py-spy dump --pid $SOME_PID
is all you need to do to dump call stacks of all threads in the $SOME_PID
process. Typically it needs escalated privileges (to read the target process' memory).
Here's an example of how it looks like for a threaded Python application.
$ sudo py-spy dump --pid 31080
Process 31080: python3.7 -m chronologer -e production serve -u www-data -m
Python v3.7.1 (/usr/local/bin/python3.7)
Thread 0x7FEF5E410400 (active): "MainThread"
_wait (cherrypy/process/wspbus.py:370)
wait (cherrypy/process/wspbus.py:384)
block (cherrypy/process/wspbus.py:321)
start (cherrypy/daemon.py:72)
serve (chronologer/cli.py:27)
main (chronologer/cli.py:84)
<module> (chronologer/__main__.py:5)
_run_code (runpy.py:85)
_run_module_as_main (runpy.py:193)
Thread 0x7FEF55636700 (active): "_TimeoutMonitor"
run (cherrypy/process/plugins.py:518)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
Thread 0x7FEF54B35700 (active): "HTTPServer Thread-2"
accept (socket.py:212)
tick (cherrypy/wsgiserver/__init__.py:2075)
start (cherrypy/wsgiserver/__init__.py:2021)
_start_http_thread (cherrypy/process/servers.py:217)
run (threading.py:865)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
...
Thread 0x7FEF2BFFF700 (idle): "CP Server Thread-10"
wait (threading.py:296)
get (queue.py:170)
run (cherrypy/wsgiserver/__init__.py:1586)
_bootstrap_inner (threading.py:917)
_bootstrap (threading.py:885)
I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."
INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there
As Arnaud suggested in a comment to the original post, you should put this in your html header:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
I don't want any cred for this. I just want to make it more visible for anyone else that come here.
The Op's Tree.insert
method qualifies for the "Gross Misnomer of the Week" award -- it doesn't insert anything. It creates a node which is not attached to any other node (not that there are any nodes to attach it to) and then the created node is trashed when the method returns.
For the edification of @Hugh Bothwell:
>>> class Foo(object):
... bar = None
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar
>>> a.bar = 42
>>> b.bar
>>> b.bar = 666
>>> a.bar
42
>>> b.bar
666
>>>
My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after
Thanks to this article, I realized (with jQuery) I can use e.pageY
and e.pageX
instead of worrying about e.offsetY/X
and e.clientY/X
issue between browsers.
Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).
I liked this event.pageY
idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.
Therefore, I can come up with a range of "clickable" region on the entire page that never changes.
Here's my demo on codepen.
or if too lazy for codepen, here's the JS:
* I only cared about the Y values for my example.
var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after
var checkRange = function(y) {
return (y >= min && y <= max);
}
box.click(function(e){
if ( checkRange(e.pageY) ) {
// do click action
box.toggleClass('toggle');
}
});
Example using Java 8.
String[] arr = {"1", "2", "3"};
String join = String.join("", arr);
I hope that helps
In the official getting started example (https://docs.docker.com/compose/gettingstarted/) with the following docker-compose.yml
:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
After you start this with docker-compose up
, you can easily shell into either your redis
container or your web
container with:
docker-compose exec redis sh
docker-compose exec web sh
It should wait until get request completed. After that I'll return get request body from where function is called.
function foo() {
var jqXHR = $.ajax({
url: url,
type: 'GET',
async: false,
});
return JSON.parse(jqXHR.responseText);
}
For the first part @thucnguyen was on the right track.
This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).
Some HTTP calls were being executed even after the activity had been closed (because it can take a while for an HTTP request to be completed). I then, through the HttpCallback
tried to update some Fragment fields and got a null
exception when trying to getActivity()
.
http.newCall(request).enqueue(new Callback(...
onResponse(Call call, Response response) {
...
getActivity().runOnUiThread(...) // <-- getActivity() was null when it had been destroyed already
IMO the solution is to prevent callbacks to occur when the fragment is no longer alive anymore (and that's not just with Okhttp).
If you have a look at the fragment lifecycle (more info here), you'll notice that there's onAttach(Context context)
and onDetach()
methods. These get called after the Fragment belongs to an activity and just before stop being so respectively.
That means that we can prevent that callback to happen by controlling it in the onDetach
method.
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Initialize HTTP we're going to use later.
http = new OkHttpClient.Builder().build();
}
@Override
public void onDetach() {
super.onDetach();
// We don't want to receive any more information about the current HTTP calls after this point.
// With Okhttp we can simply cancel the on-going ones (credits to https://github.com/square/okhttp/issues/2205#issuecomment-169363942).
for (Call call : http.dispatcher().queuedCalls()) {
call.cancel();
}
for (Call call : http.dispatcher().runningCalls()) {
call.cancel();
}
}
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
Solve it by placing the following include files and definition first:
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
See explanation here.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
converting object id to string(using toString() method) will do the job.
I fix the lack of example's library here:
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">
I think you just need to enable BrowserHistory on your router by intializing it like that : <Router history={new BrowserHistory}>
.
Before that, you should require BrowserHistory
from 'react-router/lib/BrowserHistory'
I hope that helps !
UPDATE : example in ES6
const BrowserHistory = require('react-router/lib/BrowserHistory').default;
const App = React.createClass({
render: () => {
return (
<div><button onClick={BrowserHistory.goBack}>Go Back</button></div>
);
}
});
React.render((
<Router history={BrowserHistory}>
<Route path="/" component={App} />
</Router>
), document.body);
It depends on what I'm doing. If I need a bool value (say, to determine if I'll cast to an int), I'll use is
. If I actually need the type for some reason (say, to pass to some other method) I'll use GetType()
.
<xsl:for-each select="person">
<xsl:for-each select="*">
<xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
Had a simular issue getting the same exception. Took some time locating. In my case I had a static utility class with a constructor that threw the exception (wrapping it). So my issue was in the static constructor.
For me it was not running the minify task after concatenation as it expects concatenated input and it was not generated some times.
I tried adding to a default task in execution order and it didn't worked. It worked after adding just a return
for each tasks and getting the minification inside gulp.start()
like below.
/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
return gulp.src([
'js/jquery.js',
'js/jquery-ui.js',
'js/bootstrap.js',
'js/jquery.onepage-scroll.js',
'js/script.js'])
.pipe(maps.init())
.pipe(concat('ux.js'))
.pipe(maps.write('./'))
.pipe(gulp.dest('dist/js'));
});
/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
return gulp.src('dist/js/ux.js')
.pipe(uglify())
.pipe(rename('ux.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('concat', ['concat-js'], function(){
gulp.start('minify-js');
});
gulp.task('default',['concat']);
To expand upon nosklo's explanation:
a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']
I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.
Seeing the Inner exception can help.
If you want to use a multiline EditText
with imeOptions
, try:
android:inputType="textImeMultiLine"
A variation on some of the answers above but this is how I got the value of a specific tag from the user-data script on an instance
REGION=$(curl http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')
INSTANCE_ID=$(curl -s http://instance-data/latest/meta-data/instance-id)
TAG_VALUE=$(aws ec2 describe-tags --region $REGION --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values='<TAG_NAME_HERE>'" | jq -r '.Tags[].Value')
In order to get the MySQL Database item in the Choose Data Source window, one should install the MySQL for Visual Studio package available here (the last version today is 1.2.6):
With C++11, I'd prefer following to append vector b to a:
std::move(b.begin(), b.end(), std::back_inserter(a));
when a
and b
are not overlapped, and b
is not going to be used anymore.
This is std::move
from <algorithm>
, not the usual std::move
from <utility>
.
Building on @shabunc's answer, this would allow enforcing either the key or the value — or both — to be anything you want to enforce.
type IdentifierKeys = 'my.valid.key.1' | 'my.valid.key.2';
type IdentifierValues = 'my.valid.value.1' | 'my.valid.value.2';
let stuff = new Map<IdentifierKeys, IdentifierValues>();
Should also work using enum
instead of a type
definition.
Here is an example to access response body using angular2 built in Response
import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';
@Injectable()
export class SampleService {
constructor(private http:Http) { }
getData(){
this.http.get(url)
.map((res:Response) => (
res.json() //Convert response to JSON
//OR
res.text() //Convert response to a string
))
.subscribe(data => {console.log(data)})
}
}
Well i know i am late to the party, but logging my answer here , incase, someone is facing similar issue as mine. I have faced this issue many times. 90% it gets solved by these two steps
project > properties > Build > Platform target > x64 (x32)
Test -> Test Settings > Default Processor Architecture > X64 (x32)
However i found one more common cause. The Solution files often change developer systems and they start pointing to wrong MSTest.TestAdapter. Especially if you are using custom path of nuget packages. I solved this issue by
Opening the .csproj file in notepad.
Manually correcting reference to MSTest.TestAdapter in import instructions like this.
It doesn't have an explicit delegate
keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:
private interface SingleFunc {
void printMe();
}
public static void main(String[] args) {
SingleFunc sf = () -> {
System.out.println("Hello, I am a simple single func.");
};
SingleFunc sfComplex = () -> {
System.out.println("Hello, I am a COMPLEX single func.");
};
delegate(sf);
delegate(sfComplex);
}
private static void delegate(SingleFunc f) {
f.printMe();
}
Every new object of type SingleFunc
must implement printMe()
, so it is safe to pass it to another method (e.g. delegate(SingleFunc)
) to call the printMe()
method.
Delphi used properties and they have found their way into .NET (because it has the same architect).
In Delphi they are often used in combination with runtime type information such that the integrated property editor can be used to set the property in designtime.
Properties are not always related to fields. They can be functions that possible have side effects (but of course that is very bad design).
if Ubound(yourArray)>-1 then
debug.print "The array is not empty"
else
debug.print "EMPTY"
end if
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
SELECT *
FROM customer
WHERE joiningdate >= NOW();
It depends on your purpose. If you program for the Web, avoid indexOf
, it isn't supported by Internet Explorer 6 (lot of them still used!), or do conditional use:
if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);
indexOf
is probably coded in native code, so it is faster than anything you can do in JavaScript (except binary search/dichotomy if the array is appropriate).
Note: it is a question of taste, but I would do a return false;
at the end of your routine, to return a true Boolean...
From: http://www.csharp-examples.net/string-format-datetime/
string.Format("{0:t tt}", datetime); // -> "P PM" or "A AM"
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
mybtn .setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
txtView.SetText("Your Message");
}
});
}
Try to use setStyle() in onCreate and override onCreateDialog make dialog without title
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
or just override onCreate() and setStyle fellow the code.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);
}
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
Using sql developer select the table and click on the DDL tab
You can use that code to create a new table with no data when you run it in a sql worksheet
sqldeveloper is a free to use app from oracle.
If the table has sequences or triggers the ddl will sometimes generate those for you too. You just have to be careful what order you make them in and know when to turn the triggers on or off.
You need to call the Configure
function of the XmlConfigurator
log4net.Config.XmlConfigurator.Configure();
Either call before your first loggin call or in your Global.asax like this:
protected void Application_Start(Object sender, EventArgs e) {
log4net.Config.XmlConfigurator.Configure();
}
besides pause
.
set /p=
can be used .It will expect user input and will release the flow when enter is pressed.
or
runas /user:# "" >nul 2>&1
which will do the same except nothing from the user input will be displayed nor will remain in the command history.
I experienced this when upgrading .NET Core 1.1 to 2.1.
I followed the instructions outlined here.
Try to remove <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion>
or <NetStandardImplicitPackageVersion>
section in the .csproj.
Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.
Steps
Reference
Excerpt from MSDN How to: Disable the Hosting Process
Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.
To disable the hosting process
When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.
In general, when the hosting process is disabled:
- The time needed to begin debugging .NET Framework applications increases.
- Design-time expression evaluation is unavailable.
- Partial trust debugging is unavailable.
Try this dude...
List<string> keys = new List<string>(Request.QueryString.AllKeys);
Then you will be able to search the guy for a string real easy via...
keys.Contains("someKey")
Get input1 data to send them to input2 immediately
<div>
<label>Input1</label>
<input type="text" id="input1" value="">
</div>
</br>
<label>Input2</label>
<input type="text" id="input2" value="">
<script type="text/javascript">
$(document).ready(function () {
$("#input1").keyup(function () {
var value = $(this).val();
$("#input2").val(value);
});
});
</script>
If you're trying to do this from the command line, you may be encountering an issue where a machine-wide environment variable 'Platform' is being set for you and working against you. I can reproduce this if I use the VS2012 Command window instead of a regular windows Command window.
At the command prompt type:
set platform
In a VS2012 Command window, I have a value of 'X64' preset. That seems to interfere with whatever is in my solution file.
In a regular Command window, the 'set' command results in a "variable not defined" message...which is good.
If the result of your 'set' command above returns no environment variable value, you should be good to go.
With some trial and error I learned the following.
Within the *.xml you can combine the stock fonts with the following functions, not only with typeface:
android:fontFamily="serif"
android:textStyle="italic"
With this two styles, there was no need to use typeface in any other case. The range of combinations is much more bigger with fontfamily&textStyle.
It's because you're calling doGet()
without actually implementing doGet()
. It's the default implementation of doGet() that throws the error saying the method is not supported.
you can add the following code
<a href='http://v2.immo-facile.com/catalog/admin-v2/product_info.pdf' class='btnPdf' title='pdf' target='_blank' type='application/pdf' >Télécharger la fiche du bien</a>
_x000D_
Here my own simple solution:
jQuery:
function getBootstrapBreakpoint(){
var w = $(document).innerWidth();
return (w < 768) ? 'xs' : ((w < 992) ? 'sm' : ((w < 1200) ? 'md' : 'lg'));
}
VanillaJS:
function getBootstrapBreakpoint(){
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
return (w < 768) ? 'xs' : ((w < 992) ? 'sm' : ((w < 1200) ? 'md' : 'lg'));
}
You can use Guava's Strings.repeat method:
String existingString = ...
existingString += Strings.repeat("foo", n);
Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.
constructor(props) {
super(props);
this.state ={
commentMsg: ''
}
}
onPress = () => {
alert("Hi " +this.state.commentMsg)
}
<View style={styles.sendCommentContainer}>
<TextInput
style={styles.textInput}
multiline={true}
onChangeText={(text) => this.setState({commentMsg: text})}
placeholder ='Comment'/>
<Button onPress={this.onPress}
title="OK!"
color="#841584"
/>
</TouchableOpacity>
</View>
Try my favorite: put in
~/.zshrc
this line:
PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'
don't forget
source ~/.zshrc
to test the changes
you can change the colors/color codes, of course :-)
Check this
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
I found that @Stefan Haustein comes very close to my experience, but not sure 100%. My suggestion is:
setLeft()
/ setRight()
/ setBottom()
/ setTop()
won't work sometimes.setX()
/ setY()
instead. (You might want search more in difference setLeft()
and setX()
)I think your problem is that the margin should be specified in the border tag and not in the grid.
In macOS, open the Terminal and type below command
~/.android
It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)
In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.
keytool -list -v -keystore debug.keystore
You will get the expected output.
Just use special `
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
You can see more examples here.
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
sudo npm install nodemon -g --save
Finally this worked for me. I hope this must work for others too
This should also work for other *nix varieties as well.
export GV=v0.29.0
wget "https://github.com/mozilla/geckodriver/releases/download/$GV/geckodriver-$GV-linux64.tar.gz"
tar xvzf geckodriver-$GV-linux64.tar.gz
chmod +x geckodriver
sudo cp geckodriver /usr/local/bin/
For Mac update to:
geckodriver-$GV-macos.tar.gz
For security code, please don't generate your tokens this way: $token = md5(uniqid(rand(), TRUE));
rand()
is predictableuniqid()
only adds up to 29 bits of entropymd5()
doesn't add entropy, it just mixes it deterministicallyTry this out:
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];
Sidenote: One of my employer's open source projects is an initiative to backport random_bytes()
and random_int()
into PHP 5 projects. It's MIT licensed and available on Github and Composer as paragonie/random_compat.
session_start();
if (empty($_SESSION['token'])) {
if (function_exists('mcrypt_create_iv')) {
$_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
}
}
$token = $_SESSION['token'];
Don't just use ==
or even ===
, use hash_equals()
(PHP 5.6+ only, but available to earlier versions with the hash-compat library).
if (!empty($_POST['token'])) {
if (hash_equals($_SESSION['token'], $_POST['token'])) {
// Proceed to process the form data
} else {
// Log this as a warning and keep an eye on these attempts
}
}
You can further restrict tokens to only be available for a particular form by using hash_hmac()
. HMAC is a particular keyed hash function that is safe to use, even with weaker hash functions (e.g. MD5). However, I recommend using the SHA-2 family of hash functions instead.
First, generate a second token for use as an HMAC key, then use logic like this to render it:
<input type="hidden" name="token" value="<?php
echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
?>" />
And then using a congruent operation when verifying the token:
$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
if (hash_equals($calc, $_POST['token'])) {
// Continue...
}
The tokens generated for one form cannot be reused in another context without knowing $_SESSION['second_token']
. It is important that you use a separate token as an HMAC key than the one you just drop on the page.
Anyone who uses the Twig templating engine can benefit from a simplified dual strategy by adding this filter to their Twig environment:
$twigEnv->addFunction(
new \Twig_SimpleFunction(
'form_token',
function($lock_to = null) {
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
if (empty($_SESSION['token2'])) {
$_SESSION['token2'] = random_bytes(32);
}
if (empty($lock_to)) {
return $_SESSION['token'];
}
return hash_hmac('sha256', $lock_to, $_SESSION['token2']);
}
)
);
With this Twig function, you can use both the general purpose tokens like so:
<input type="hidden" name="token" value="{{ form_token() }}" />
Or the locked down variant:
<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />
Twig is only concerned with template rendering; you still must validate the tokens properly. In my opinion, the Twig strategy offers greater flexibility and simplicity, while maintaining the possibility for maximum security.
If you have a security requirement that each CSRF token is allowed to be usable exactly once, the simplest strategy regenerate it after each successful validation. However, doing so will invalidate every previous token which doesn't mix well with people who browse multiple tabs at once.
Paragon Initiative Enterprises maintains an Anti-CSRF library for these corner cases. It works with one-use per-form tokens, exclusively. When enough tokens are stored in the session data (default configuration: 65535), it will cycle out the oldest unredeemed tokens first.
while some_condition:
...
if condition_a:
# do something
break
...
if condition_b:
# do something
break
# more code here
break
:hover
is a pseudoclass, so you can put your CSS declarations there:
a:hover {
color: #f00;
}
You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:
.some-class,
a:hover {
color: #f00;
}
Abstraction
Abstraction is the process of extracting out the common properties and fields of all existing and foreseen implementations.
For example: Car is an abstraction for Sedan, Hatchback, SUV, Coupe, Convertible. Car would have all the properties and fields common to all types of cars.
Encapsulation
Encapsulation is the process of hiding unwanted details from the user. This term comes from the Capsule. Just like medicine is hidden from the user inside the capsule. Details of various machines and equipments and devices ranging from Mixers, Bikes, Washing machines, Radio, Television to Airplanes. You don't want all the details of the machine to be visible to user.
In programming terms: Let us consider a class Car. In the example below, all that user needs to know is turn the key (turnKey() method), he does not know about the internal functions. User does not need to know about any of the internal functions or about the internal components.
In this case, all the private methods are internal functions and private fields like 'Piston p1' are internal data which user does not need to know.
public class Car{
private void startMotor(){ //do something }
private void generateVoltage(){ //do something }
private void sparkPlugIgnition(){ //do something }
private void fuelFlowFromTankToInjector(){ //do something }
private void pushPistonsDown() {
p1.doAction();
p2.doAction();
//do something }
private void moveCrankShaft(){ //do something }
private Piston p1;
private Piston p2;
public void turnKey(){
startMotor();
generateVoltage();
sparkPlugIgnition();
fuelFlowFromTankToInjector();
pushPistonsDown();
moveCrankShat();
...
}
}
C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.
C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.
C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
This depends upon scenarios.
Let's say you have some business functionality and you need to process something with that value further but having null
value at time of processing would impact it.
Then, in that case, you can use Optional<?>
.
String nullName = null;
String name = Optional.ofNullable(nullName)
.map(<doSomething>)
.orElse("Default value in case of null");
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
Dynamically:
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });
Via xml:
<EditText
android:maxLength="@integer/max_edittext_length"