This works with my IP camera:
import cv2
#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")
while True:
#print('About to start the Read command')
ret, frame = cap.read()
#print('About to show frame of Video.')
cv2.imshow("Capturing",frame)
#print('Running..')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I found the Stream URL in the Camera's Setup screen:
Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)
Anyone who is wondering how to get the image extension then you can try split method of string on image url:
str_arr = str(img_url).split('.')
img_ext = '.' + str_arr[3] #www.bigbasket.com/patanjali-atta.jpg (jpg is after 3rd dot so)
img_data = requests.get(img_url).content
with open(img_name + img_ext, 'wb') as handler:
handler.write(img_data)
I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.
In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "customerEntityManager",
transactionManagerRef = "customerTransactionManager",
basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {
The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:
em.setPackagesToScan("com.mm.boot.multidb.model.customer");
Also the injection of proper EntityManagerFactory did not work. It should be:
@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
}
The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.
The last thing I have done was to disable to automatic configuration of JpaRepositories:
@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)
And with all fixes the application starts as you probably expect!
We had the same issue when we had a typo in the mybatis mapping file like
....
#{column1Name, jdbcType=INTEGER},
#{column2Name, jdbcType=VARCHAR},
#{column3Name, jdbcTyep=VARCHAR} -- do you see the typo ?
.....
So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.
I agree with above answer. But here is another way of CSS compression.
You can concat your CSS by using YUI compressor:
module.exports = function(grunt) {
var exec = require('child_process').exec;
grunt.registerTask('cssmin', function() {
var cmd = 'java -jar -Xss2048k '
+ __dirname + '/../yuicompressor-2.4.7.jar --type css '
+ grunt.template.process('/css/style.css') + ' -o '
+ grunt.template.process('/css/style.min.css')
exec(cmd, function(err, stdout, stderr) {
if(err) throw err;
});
});
};
You have a TH floating at the top of your table which isn't within a TR. Fix that.
With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.
You also have a closing tag which shouldn't be there.
It should be:
<img src="h.gif" alt="" border="3" height="100" width="100" />
Also this:
<table border = 5 bordercolor = red align = center>
Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.
Should be:
<table border="5" bordercolor="red" align="center">
Also you have no DOCTYPE declared. You should at least add:
<!DOCTYPE html>
You are reusing the customer
reference. Java works by reference for Obejcts. Not for primitives.
What you are doing is adding to the list the same customer
and then modifying it. Thus setting the same values for all of objects. That's why you see the last. Because all are the same.
while (rs.next()) {
Customer customer = new Customer();
customer.setId(rs.getInt("id"));
...
Here's a more portable version (just for fun, it is not necessary in your case):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here
public void setHoursWorked(){
hoursWorked = hours;
}
You haven't defined hours
inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.
By far the easiest solution is to just use the Google Chart API http://code.google.com/apis/chart/
You can make bar graphs, pie charts, use 3D, and it's as easy as building a url with some parameters. See the simple example below.
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
As the names imply, a HashMap is an associative Map (mapping from a key to a value), a HashSet is just a Set.
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
In my system (Ubuntu 12.04) I found RESET QUERY CACHE
and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
and then reset the query cache in mysql client:
RESET QUERY CACHE;
With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:
[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
It's worth mentioning that json_pp
comes pre-installed with Ubuntu 12.04 (at least) and Debian in /usr/bin/json_pp
I have been looking for the best way to do that since not every method we want to call is located in Fragment with same Activity Parent.
In your Fragment
public void methodExemple(View view){
// your code here
Toast.makeText(view.getContext(), "Clicked clicked",Toast.LENGTH_LONG).show();
}
In your Activity
new ExempleFragment().methodExemple(context);
In case you don't have the indices of the elements you want to remove, you can use the function in1d provided by numpy.
The function returns True
if the element of a 1-D array is also present in a second array. To delete the elements, you just have to negate the values returned by this function.
Notice that this method keeps the order from the original array.
In [1]: import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
rm = np.array([3, 4, 7])
# np.in1d return true if the element of `a` is in `rm`
idx = np.in1d(a, rm)
idx
Out[1]: array([False, False, True, True, False, False, True, False, False])
In [2]: # Since we want the opposite of what `in1d` gives us,
# you just have to negate the returned value
a[~idx]
Out[2]: array([1, 2, 5, 6, 8, 9])
I'm using this to address the security implications noted in @CMS's answer.
// example 1: www.example.com/index.html#foo
// load correct subpage from URL hash if it exists
$(window).on('load', function () {
var hash = window.location.hash;
if (hash) {
hash = hash.replace('#',''); // strip the # at the beginning of the string
hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
hash = '#' + hash; // hash now equals #foo with example 1
// do stuff with hash
$( 'ul' + hash + ':first' ).show();
// etc...
}
});
var o = ...
var proto = Object.getPrototypeOf(o);
proto === SomeThing;
Keep a handle on the prototype you expect the object to have, then compare against it.
for example
var o = "someString";
var proto = Object.getPrototypeOf(o);
proto === String.prototype; // true
Rephrasing Yuri, Fábio, and Frosts answers for the Django noob (i.e. me) - almost certainly a simplification, but a good starting point?
render_to_response()
is the "original", but requires you putting context_instance=RequestContext(request)
in nearly all the time, a PITA.
direct_to_template()
is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext
render()
is a shortcut for render_to_response()
that automatically supplies context_instance=Request
....
Its available in the django development version (1.2.1) but many have created their own shortcuts such as this one, this one or the one that threw me initially, Nathans basic.tools.shortcuts.py
All answers above - do not work. So I will put here a function that works on 4 and 9 android
private String getCurrentLanguage(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
return LocaleList.getDefault().get(0).getLanguage();
} else{
return Locale.getDefault().getLanguage();
}
}
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
Do it in the controller
$timeout(function(){
$scope.checked = true;
}, 1);
_x000D_
then remove ng-checked.
You should update eslint config file to fix this permanently. Else you can temporarily enable or disable eslint check for console like below
/* eslint-disable no-console */
console.log(someThing);
/* eslint-enable no-console */
to change the object owner try the following
EXEC sp_changedbowner 'sa'
that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
#!/usr/bin/python
count = 0
f = open('last_line1','r')
for line in f.readlines():
line = line.strip()
count = count + 1
print line
print count
f.close()
count1 = 0
h = open('last_line1','r')
for line in h.readlines():
line = line.strip()
count1 = count1 + 1
if count1 == count:
print line #-------------------- this is the last line
h.close()
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
Instead of using the autoupdater, we just set the properties of the EXE file to read-only. That way it doesn’t delete the file.
return true not work
return false working
found = false;
query = "foo";
$('.items').each(function()
{
if($(this).text() == query)
{
found = true;
return false;
}
});
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
There are 3 ways to handle this :-
Bind the method in constructor as :-
export class HeaderRows extends Component {
constructor() {
super();
this.handleSort = this.handleSort.bind(this);
}
}
Use the arrow function while creating it as :-
handleSort = () => {
// some text here
}
Third way is this :-
<th value={column} onClick={() => that.handleSort} >{column}</th>
One of many reasons is xampp cannot start MySQL service by itself. Everything you need to do is run mySQL service manually.
First, make sure that 'mysqld.exe' is not running, if have, end it. (go to Task Manager > Progresses Tab > right click 'mysqld.exe' > end task)
Open your services.msc by Run (press 'Window + R') > services.msc or 0n your XAMPP ControlPanel, click 'Services' button. Find 'MySQL' service, right click and run it.
Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer
works both in browser and Node. See documentation for all features.
If you're using the HTML5 Fetch API to make POST requests as a logged in user and getting Forbidden (CSRF cookie not set.)
, it could be because by default fetch
does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.
You can include the session token by passing the option credentials: 'include'
to fetch:
var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
method: 'POST',
body: payload,
headers: headers,
credentials: 'include'
})
If you want to pass class instances (objects), you either use
void function(const MyClass& object){
// do something with object
}
or
void process(MyClass& object_to_be_changed){
// change member variables
}
On the other hand if you want to "pass" the class itself
template<class AnyClass>
void function_taking_class(){
// use static functions of AnyClass
AnyClass::count_instances();
// or create an object of AnyClass and use it
AnyClass object;
object.member = value;
}
// call it as
function_taking_class<MyClass>();
// or
function_taking_class<MyStruct>();
with
class MyClass{
int member;
//...
};
MyClass object1;
Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.texture);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
Shader.TileMode.REPEAT);
setBackground(bitmapDrawable);
}
This is the Linux out of memory manager (OOM). Your process was selected due to 'badness' - a combination of recentness, resident size (memory in use, rather than just allocated) and other factors.
sudo journalctl -xb
You'll see a message like:
Jul 20 11:05:00 someapp kernel: Mem-Info:
Jul 20 11:05:00 someapp kernel: Node 0 DMA per-cpu:
Jul 20 11:05:00 someapp kernel: CPU 0: hi: 0, btch: 1 usd: 0
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 per-cpu:
Jul 20 11:05:00 someapp kernel: CPU 0: hi: 186, btch: 31 usd: 30
Jul 20 11:05:00 someapp kernel: active_anon:206043 inactive_anon:6347 isolated_anon:0
active_file:722 inactive_file:4126 isolated_file:0
unevictable:0 dirty:5 writeback:0 unstable:0
free:12202 slab_reclaimable:3849 slab_unreclaimable:14574
mapped:792 shmem:12802 pagetables:1651 bounce:0
free_cma:0
Jul 20 11:05:00 someapp kernel: Node 0 DMA free:4576kB min:708kB low:884kB high:1060kB active_anon:10012kB inactive_anon:488kB active_file:4kB inactive_file:4kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 968 968 968
Jul 20 11:05:00 someapp kernel: Node 0 DMA32 free:44232kB min:44344kB low:55428kB high:66516kB active_anon:814160kB inactive_anon:24900kB active_file:2884kB inactive_file:16500kB unevictable:0kB isolated(anon):0kB isolated
Jul 20 11:05:00 someapp kernel: lowmem_reserve[]: 0 0 0 0
Jul 20 11:05:00 someapp kernel: Node 0 DMA: 17*4kB (UEM) 22*8kB (UEM) 15*16kB (UEM) 12*32kB (UEM) 8*64kB (E) 9*128kB (UEM) 2*256kB (UE) 3*512kB (UM) 0*1024kB 0*2048kB 0*4096kB = 4580kB
Jul 20 11:05:00 someapp kernel: Node 0 DMA32: 216*4kB (UE) 601*8kB (UE) 448*16kB (UE) 311*32kB (UEM) 135*64kB (UEM) 74*128kB (UEM) 5*256kB (EM) 0*512kB 0*1024kB 1*2048kB (R) 0*4096kB = 44232kB
Jul 20 11:05:00 someapp kernel: Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB
Jul 20 11:05:00 someapp kernel: 17656 total pagecache pages
Jul 20 11:05:00 someapp kernel: 0 pages in swap cache
Jul 20 11:05:00 someapp kernel: Swap cache stats: add 0, delete 0, find 0/0
Jul 20 11:05:00 someapp kernel: Free swap = 0kB
Jul 20 11:05:00 someapp kernel: Total swap = 0kB
Jul 20 11:05:00 someapp kernel: 262141 pages RAM
Jul 20 11:05:00 someapp kernel: 7645 pages reserved
Jul 20 11:05:00 someapp kernel: 264073 pages shared
Jul 20 11:05:00 someapp kernel: 240240 pages non-shared
Jul 20 11:05:00 someapp kernel: [ pid ] uid tgid total_vm rss nr_ptes swapents oom_score_adj name
Jul 20 11:05:00 someapp kernel: [ 241] 0 241 13581 1610 26 0 0 systemd-journal
Jul 20 11:05:00 someapp kernel: [ 246] 0 246 10494 133 22 0 -1000 systemd-udevd
Jul 20 11:05:00 someapp kernel: [ 264] 0 264 29174 121 26 0 -1000 auditd
Jul 20 11:05:00 someapp kernel: [ 342] 0 342 94449 466 67 0 0 NetworkManager
Jul 20 11:05:00 someapp kernel: [ 346] 0 346 137495 3125 88 0 0 tuned
Jul 20 11:05:00 someapp kernel: [ 348] 0 348 79595 726 60 0 0 rsyslogd
Jul 20 11:05:00 someapp kernel: [ 353] 70 353 6986 72 19 0 0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [ 362] 70 362 6986 58 18 0 0 avahi-daemon
Jul 20 11:05:00 someapp kernel: [ 378] 0 378 1621 25 8 0 0 iprinit
Jul 20 11:05:00 someapp kernel: [ 380] 0 380 1621 26 9 0 0 iprupdate
Jul 20 11:05:00 someapp kernel: [ 384] 81 384 6676 142 18 0 -900 dbus-daemon
Jul 20 11:05:00 someapp kernel: [ 385] 0 385 8671 83 21 0 0 systemd-logind
Jul 20 11:05:00 someapp kernel: [ 386] 0 386 31573 153 15 0 0 crond
Jul 20 11:05:00 someapp kernel: [ 391] 999 391 128531 2440 48 0 0 polkitd
Jul 20 11:05:00 someapp kernel: [ 400] 0 400 9781 23 8 0 0 iprdump
Jul 20 11:05:00 someapp kernel: [ 419] 0 419 27501 32 10 0 0 agetty
Jul 20 11:05:00 someapp kernel: [ 855] 0 855 22883 258 43 0 0 master
Jul 20 11:05:00 someapp kernel: [ 862] 89 862 22926 254 44 0 0 qmgr
Jul 20 11:05:00 someapp kernel: [23631] 0 23631 20698 211 43 0 -1000 sshd
Jul 20 11:05:00 someapp kernel: [12884] 0 12884 81885 3754 80 0 0 firewalld
Jul 20 11:05:00 someapp kernel: [18130] 0 18130 33359 291 65 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18132] 1000 18132 33791 748 64 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18133] 1000 18133 28867 122 13 0 0 bash
Jul 20 11:05:00 someapp kernel: [18428] 99 18428 208627 42909 151 0 0 node
Jul 20 11:05:00 someapp kernel: [18486] 89 18486 22909 250 46 0 0 pickup
Jul 20 11:05:00 someapp kernel: [18515] 1000 18515 352905 141851 470 0 0 npm
Jul 20 11:05:00 someapp kernel: [18520] 0 18520 33359 291 66 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18522] 1000 18522 33359 294 64 0 0 sshd
Jul 20 11:05:00 someapp kernel: [18523] 1000 18523 28866 115 12 0 0 bash
Jul 20 11:05:00 someapp kernel: Out of memory: Kill process 18515 (npm) score 559 or sacrifice child
Jul 20 11:05:00 someapp kernel: Killed process 18515 (npm) total-vm:1411620kB, anon-rss:567404kB, file-rss:0kB
similar to the rest, but more specific:
table.borderless td,table.borderless th{
border: none !important;
}
There is a good article on MDN that explains the theory behind those concepts: https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements
It also explains the important conceptual differences between boundingClientRect's width/height vs offsetWidth/offsetHeight.
Then, to prove the theory right or wrong, you need some tests. That's what I did here: https://github.com/lingtalfi/dimensions-cheatsheet
It's testing for chrome53, ff49, safari9, edge13 and ie11.
The results of the tests prove that the theory is generally right. For the tests, I created 3 divs containing 10 lorem ipsum paragraphs each. Some css was applied to them:
.div1{
width: 500px;
height: 300px;
padding: 10px;
border: 5px solid black;
overflow: auto;
}
.div2{
width: 500px;
height: 300px;
padding: 10px;
border: 5px solid black;
box-sizing: border-box;
overflow: auto;
}
.div3{
width: 500px;
height: 300px;
padding: 10px;
border: 5px solid black;
overflow: auto;
transform: scale(0.5);
}
And here are the results:
div1
bcr.height: 330 (chrome53, ff49, safari9, edge13, ie11)
clientWidth: 505 (chrome53, ff49, safari9)
clientHeight: 320 (chrome53, ff49, safari9, edge13, ie11)
scrollWidth: 505 (chrome53, safari9, ff49)
div2
clientHeight: 290 (chrome53, ff49, safari9, edge13, ie11)
scrollWidth: 475 (chrome53, safari9, ff49)
div3
clientHeight: 320 (chrome53, ff49, safari9, edge13, ie11)
scrollWidth: 505 (chrome53, safari9, ff49)
So, apart from the boundingClientRect's height value (299.9999694824219 instead of expected 300) in edge13 and ie11, the results confirm that the theory behind this works.
From there, here is my definition of those concepts:
Note: the default vertical scroll bar's width is 12px in edge13, 15px in chrome53, ff49 and safari9, and 17px in ie11 (done by measurements in photoshop from screenshots, and proven right by the results of the tests).
However, in some cases, maybe your app is not using the default vertical scroll bar's width.
So, given the definitions of those concepts, the vertical scroll bar's width should be equal to (in pseudo code):
layout dimension: offsetWidth - clientWidth - (borderLeftWidth + borderRightWidth)
rendering dimension: boundingClientRect.width - clientWidth - (borderLeftWidth + borderRightWidth)
Note, if you don't understand layout vs rendering please read the mdn article.
Also, if you have another browser (or if you want to see the results of the tests for yourself), you can see my test page here: http://codepen.io/lingtalfi/pen/BLdBdL
Based on muhuk answer I did this simple tag encapsulating python string.format
method.
templatetags
at your's application folder. format.py
file on it.Add this to it:
from django import template
register = template.Library()
@register.filter(name='format')
def format(value, fmt):
return fmt.format(value)
{% load format %}
{{ some_value|format:"{:0.2f}" }}
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.
Example:
cout << "\033[1;31mbold red text\033[0m\n";
Here, \033
is the ESC character, ASCII 27. It is followed by [
, then zero or more numbers separated by ;
, and finally the letter m
. The numbers describe the colour and format to switch to from that point onwards.
The codes for foreground and background colours are:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
Additionally, you can use these:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27
See the table on Wikipedia for other, less widely supported codes.
To determine whether your terminal supports colour sequences, read the value of the TERM
environment variable. It should specify the particular terminal type used (e.g. vt100
, gnome-terminal
, xterm
, screen
, ...). Then look that up in the terminfo database; check the colors
capability.
In my case I wanted to achieve format "HH:MM:SS.fff". I solved it like this:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
For window if you download scr folder say apache-jmeter-5.3_src then you won't find ApacheJMeter.jar file insider bin folder.One might have downloaded zip file under source section. Form this link download zip file under binaries section and click on ApacheJMeter.jar from bin folder https://jmeter.apache.org/download_jmeter.cgi
You could have simply used Range("x1").value(11)
something like below:
Sheets("Output").Range("$A$1:$A$500").value(11) = Sheets(sheet_).Range("$A$1:$A$500").value(11)
range has default property "Value" plus value can have 3 optional orguments 10,11,12. 11 is what you need to tansfer both value and formats. It doesn't use clipboard so it is faster.- Durgesh
std::fill(a.begin(),a.end(),0);
This is also useful if you only want to temporarily suppress the warning:
import matplotlib.pyplot as plt
with plt.rc_context(rc={'figure.max_open_warning': 0}):
lots_of_plots()
If by "hex data" you mean a string of the form
s = "6a48f82d8e828ce82b82"
you can use
i = int(s, 16)
to convert it to an integer and
str(i)
to convert it to a decimal string.
The same error occurs also when doing SELECT DISTINCT ..., <CLOB_column>, ...
.
If this CLOB column contains values shorter than limit for VARCHAR2 in all the applicable rows you may use to_char(<CLOB_column>)
or concatenate results of multiple calls to DBMS_LOB.SUBSTR(<CLOB_column>, ...)
.
$('selector').css('cursor', 'pointer'); // 'default' to revert
I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".
The normal arrow cursor is just "default".
You may want to use async/await, since node v10.0.0
it's possible with the built-in fs Promises API
.
Example:
const fs = require('fs')
const copyFile = async (src, dest) => {
await fs.promises.copyFile(src, dest)
}
Note:
As of
node v11.14.0, v10.17.0
the API is no longer experimental.
More information:
The consensus answer above is good but if you've got problems running queries within stored procedures after fixing your my.cnf file, then try loading your SPs again.
I suspect MySQL must have compiled the SPs with the default only_full_group_by set originally. Therefore, even when I changed my.cnf and restarted mysqld it had no effect on the SPs, and they kept failing with "SELECT list is not in GROUP BY clause and contains nonaggregated column ... which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by".
Reloading the SPs must have caused them to be recompiled now with only_full_group_by disabled. After that, they seem to work as expected.
The technically best way is probably this here:
private static async Task AppendLineToFileAsync([NotNull] string path, string line)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentOutOfRangeException(nameof(path), path, "Was null or whitepsace.");
if (!File.Exists(path))
throw new FileNotFoundException("File not found.", nameof(path));
using (var file = File.Open(path, FileMode.Append, FileAccess.Write))
using (var writer = new StreamWriter(file))
{
await writer.WriteLineAsync(line);
await writer.FlushAsync();
}
}
**<HEAD>**
< link rel="icon" href="directory/image.png">
Then run and enjoy it
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.
Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:
class Given { ... } // API specified fields; or maybe it's just Object {}
interface PropAble extends Given {
props?: string; // you can cast any Given to this and set .props
// '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";
// to avoid constantly casting:
let k:PropAble = getTheGivenObject();
k.props = "value for props";
The fastest way I found was this:
var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);
Namespace: System.Web.Script.Serialization.JavaScriptSerializer
CURRENT_TIMESTAMP
is only acceptable on TIMESTAMP
fields. DATETIME
fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.
relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
Responding to @1290. Sorry, no way to format blocks in comments. The None
value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString
. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None)
produces 'None'
, a non-blank string.
However if you must treat None
and (spaces) as "blank" strings, here is a better way:
class weirdstr(str):
def __new__(cls, content):
return str.__new__(cls, content if content is not None else '')
def __nonzero__(self):
return bool(self.strip())
Examples:
>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True
>>> spaces = weirdstr(' ')
>>> print spaces, bool(spaces)
False
>>> blank = weirdstr('')
>>> print blank, bool(blank)
False
>>> none = weirdstr(None)
>>> print none, bool(none)
False
>>> if not spaces:
... print 'This is a so-called blank string'
...
This is a so-called blank string
Meets the @rouble requirements while not breaking the expected bool
behavior of strings.
#Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))
#create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth]
odd_numbers = []
#filter list and add odd numbers to new list
for value in sorted_list:
if value%2 != 0:
odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)
There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime()
and TimeUnit.NANOSECONDS
as the time unit. Why should I do this? Well, it is because System.nanoTime()
method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
For the same reason, it is recommended to avoid the use of the System.currentTimeMillis()
method for measuring elapsed time. This method returns the wall-clock
time, which may change based on many factors. This will be negative for your measurements.
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
So here you have one solution based on the System.nanoTime()
method, another one using Guava, and the final one Apache Commons Lang
public class TimeBenchUtil
{
public static void main(String[] args) throws InterruptedException
{
stopWatch();
stopWatchGuava();
stopWatchApacheCommons();
}
public static void stopWatch() throws InterruptedException
{
long endTime, timeElapsed, startTime = System.nanoTime();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
endTime = System.nanoTime();
// get difference of two nanoTime values
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchGuava() throws InterruptedException
{
// Creates and starts a new stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // optional
// get elapsed time, expressed in milliseconds
long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchApacheCommons() throws InterruptedException
{
StopWatch stopwatch = new StopWatch();
stopwatch.start();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // Optional
long timeElapsed = stopwatch.getNanoTime();
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
}
I agree with using the ?? operator.
If you're dealing with strings use if(String.IsNullOrEmpty(myStr))
From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .
router.navigateByUrl() is used for absolute path navigation.
ie,
If we need to navigate to entirely different route in that case we can use router.navigateByUrl
For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()
Syntax :
router.navigateByUrl(' ---- String ----');
router.navigate([], {relativeTo: route})
To clarify how the shebang line works for windows, from the 3.7 Python doc:
Try
NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];
Not the greatest, but this should work:
sed -i 'Ns/.*/replacement-line/' file.txt
where N
should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i
option:
sed 'Ns/.*/replacement-line/' file.txt > new_file.txt
Try it
Thread.currentThread().getStackTrace()[1].getClassName()
Or
Thread.currentThread().getStackTrace()[2].getClassName()
I found a quick and easy solution to what I wanted using json_normalize()
included in pandas 1.01
.
from urllib2 import Request, urlopen
import json
import pandas as pd
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])
This gives a nice flattened dataframe with the json data that I got from the Google Maps API.
ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.
BASE stands for -
Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.
Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.
Starting Mongo 4.2
, it's also possible to use a slightly different syntax:
// { name: "book", tags: { words: ["abc", "123"], lat: 33, long: 22 } }
db.collection.update({}, [{ $unset: ["tags.words"] }], { many: true })
// { name: "book", tags: { lat: 33, long: 22 } }
The update method can also accept an aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline).
This means the $unset
operator being used is the aggregation one (as opposed to the "query" one), whose syntax takes an array of fields.
The first thing to do is to determine your definition of "line of code" (LOC). In both your question
It counts a line with just one } as a line and he doesn't want that to count as "its not a line, its a style choice"
and in the answers, e.g.,
You can adjust the Lines of Code metrics by ignoring blank and comment-only lines or exclude Javadoc if you want
you can tell that people have different opinions as to what constitutes a line of code. In particular, people are often imprecise about whether they really want the number of lines of code or the number of statements. For example, if you have the following really long line filled with statements, what do you want to report, 1 LOC or hundreds of statements?
{ a = 1; b = 2; if (a==c) b++; /* etc. for another 1000 characters */ }
And when somebody asks you what you are calling a LOC, make sure you can answer, even if it is just "my definition of a LOC is Metrics2's definition". In general, for most commonly formatted code (unlike my example), the popular tools will give numbers fairly similar, so Metrics2, SonarQube, etc. should all be fine, as long as you use them consistently. In other words, don't count the LOC of some code using one tool and compare that value to a later version of that code that was measured with a different tool.
If you want to do it without a plugin you could use the following.
Javascript, using jQuery:
$(document).ready( function (){
$("#your_form").submit( function(submitEvent) {
// get the file name, possibly with path (depends on browser)
var filename = $("#file_input").val();
// Use a regular expression to trim everything before final dot
var extension = filename.replace(/^.*\./, '');
// Iff there is no dot anywhere in filename, we would have extension == filename,
// so we account for this possibility now
if (extension == filename) {
extension = '';
} else {
// if there is an extension, we convert to lower case
// (N.B. this conversion will not effect the value of the extension
// on the file upload.)
extension = extension.toLowerCase();
}
switch (extension) {
case 'jpg':
case 'jpeg':
case 'png':
alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)");
// uncomment the next line to allow the form to submitted in this case:
// break;
default:
// Cancel the form submission
submitEvent.preventDefault();
}
});
});
HTML:
<form id="your_form" method="post" enctype="multipart/form-data">
<input id="file_input" type="file" />
<input type="submit">
</form>
Everything is encoded by default!!! This is pretty huge.
Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.
You can make a section required which is nice.
One additional reason to use a typedef for the superclass is when you are using complex templates in the object's inheritance.
For instance:
template <typename T, size_t C, typename U>
class A
{ ... };
template <typename T>
class B : public A<T,99,T>
{ ... };
In class B it would be ideal to have a typedef for A otherwise you would be stuck repeating it everywhere you wanted to reference A's members.
In these cases it can work with multiple inheritance too, but you wouldn't have a typedef named 'super', it would be called 'base_A_t' or something like that.
--jeffk++
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
I am siteConfiguration class for calling all my appSetting like this way. I share it if it will help anyone.
add the following code at the "web.config"
<configuration>
<configSections>
<!-- some stuff omitted here -->
</configSections>
<appSettings>
<add key="appKeyString" value="abc" />
<add key="appKeyInt" value="123" />
</appSettings>
</configuration>
Now you can define a class for getting all your appSetting value. like this
using System;
using System.Configuration;
namespace Configuration
{
public static class SiteConfigurationReader
{
public static String appKeyString //for string type value
{
get
{
return ConfigurationManager.AppSettings.Get("appKeyString");
}
}
public static Int32 appKeyInt //to get integer value
{
get
{
return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true);
}
}
// you can also get the app setting by passing the key
public static Int32 GetAppSettingsInteger(string keyName)
{
try
{
return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName));
}
catch
{
return 0;
}
}
}
}
Now add the reference of previous class and to access a key call like bellow
string appKeyStringVal= SiteConfigurationReader.appKeyString;
int appKeyIntVal= SiteConfigurationReader.appKeyInt;
int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
I appreciate this is an old post, but it may be useful for people to know that the Azure Migration Wizard (available on Codeplex - can't link to is as Codeplex is at the moment I'm typing this) will do this easily.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
You can use in the below format, Raw default value starting from 0, so
You can assign your own specific start value.
typedef enum : NSUInteger {
kCircle, // for your value; kCircle = 5, ...
kRectangle,
kOblateSpheroid
} ShapeType;
ShapeType circleShape = kCircle;
NSLog(@"%lu", (unsigned long) circleShape); // prints: 0
After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.
Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
Map<String, DataSet> result = new HashMap<>();
multiDataPoints.forEach(pt ->
pt.keyToData.forEach((key, value) ->
result.computeIfAbsent(
key, k -> new DataSet(k, new ArrayList<>()))
.dataPoints.add(new DataPoint(pt.timestamp, value))));
return result.values();
}
Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
new Object() {
String key = e.getKey();
DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
}))
.collect(
collectingAndThen(
groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}
Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.map(mdp -> mdp.keyToData.entrySet().stream()
.collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
.reduce(new HashMap<>(), mapMerger())
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:
<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
return (lhs, rhs) -> {
Map<K, List<V>> result = new HashMap<>();
lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
return result;
};
}
This is my preferred version using a class based view. Simply subclass the basic View and override the get()-method.
import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/json" )
I had a similar issue, and my solution is ugly, but it works:
void showCode() {
hideRegisterMessage(); // Hides view
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
showRegisterMessage(); // Shows view
}
}, 3000); // After 3 seconds
}
The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).
In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character
So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).
And you can mix “combining above” and “combining below” marks.
The sample text in the question starts with:
H
ͭ
̓
̓
̇
The equivalent in Java to a struct would be
class Member
{
public String FirstName;
public String LastName;
public int BirthYear;
};
and there's nothing wrong with that in the right circumstances. Much the same as in C++ really in terms of when do you use struct verses when do you use a class with encapsulated data.
--
-- STORED PROCEDURE
-- Name of stored procedure.
--
-- DESCRIPTION
-- Business description of the stored procedure's functionality.
--
-- PARAMETERS
-- @InputParameter1
-- * Description of @InputParameter1 and how it is used.
--
-- RETURN VALUE
-- 0 - No Error.
-- -1000 - Description of cause of non-zero return value.
--
-- PROGRAMMING NOTES
-- Gotchas and other notes for your fellow programmer.
--
-- CHANGE HISTORY
-- 05 May 2009 - Who
-- * More comprehensive description of the change than that included with the
-- source code commit message.
--
Take a look at ImageView.ScaleType to control and understand the way resizing happens in an ImageView
. When the image is resized (while maintaining its aspect ratio), chances are that either the image's height or width becomes smaller than ImageView
's dimensions.
I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.
<script>
let browserName = "";
if(navigator.vendor.match(/google/i)) {
browserName = 'chrome/blink';
}
else if(navigator.vendor.match(/apple/i)) {
browserName = 'safari/webkit';
}
else if(navigator.userAgent.match(/firefox\//i)) {
browserName = 'firefox/gecko';
}
else if(navigator.userAgent.match(/edge\//i)) {
browserName = 'edge/edgehtml';
}
else if(navigator.userAgent.match(/trident\//i)) {
browserName = 'ie/trident';
}
else
{
browserName = navigator.userAgent + "\n" + navigator.vendor;
}
alert(browserName);
</script>
To clarify:
Just to point out the generic way to iterate over any map:
private <K, V> void iterateOverMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
}
}
If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";
Yes I got the trick.
public void onClick(View v) {
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
imgDisplay.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION );
}
else if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
imgDisplay.setSystemUiVisibility( View.STATUS_BAR_HIDDEN );
else{}
}
But it didn't solve my problem completely. I want to hide the horizontal scrollview too, which is in front of the imageView (below), which can't be hidden in this.
I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:
return iterator._Ptr;
While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
Compiling answers given by @adurdin and @User
Add followings to your info.plist & change localhost.com
with your corresponding domain name, you can add multiple domains as well:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<false/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSRequiresCertificateTransparency</key>
<false/>
</dict>
</dict>
</dict>
</plist>
You info.plist must looks like this:
Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.
So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.
The recommended way to install setuptools on Windows is to download ez_setup.py and run it. The script will download the appropriate .egg file and install it for you.
For best results, uninstall previous versions FIRST (see Uninstalling).
Once installation is complete, you will find an easy_install.exe program in your Python Scripts subdirectory. For simple invocation and best results, add this directory to your PATH environment variable, if it is not already present.
more details : https://pypi.python.org/pypi/setuptools
I'll have to add an answer here, because the other answers are either not covering my case or are needlessly complicated.
I use github with other developers and I just want all the local branches whose remotes were (possibly merged and) deleted from a github PR to be deleted in one go from my machine. No, things like git branch -r --merged
don't cover the branches that were not merged locally, or the ones that were not merged at all (abandoned) etc, so a different solution is needed.
Anyway, the first step I got it from other answers:
git fetch --prune
A dry run of git remote prune origin
seemed like it would do the same thing in my case, so I went with the shortest version to keep it simple.
Now, a git branch -v
should mark the branches whose remotes are deleted as [gone]
.
Therefore, all I need to do is:
git branch -v|grep \\[gone\\]|awk '{print $1}'|xargs -I{} git branch -D {}
As simple as that, it deletes everything I want for the above scenario.
The less common xargs
syntax is so that it also works on Mac & BSD in addition to Linux.
Careful, this command is not a dry run so it will force-delete all the branches marked as [gone]
. Obviously, this being git nothing is gone forever, if you see branches deleted that you remember you wanted kept you can always undelete them (the above command will have listed their hash on deletion, so a simple git checkout -b <branch> <hash>
.
Edit: Just add this alias to your .bashrc/.bash_profile, the two commands made into one and I updated the second to work on all shells:
alias old_branch_delete='git fetch -p && git branch -vv | awk "/: gone]/{print \$1}" | xargs git branch -D'
You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
In PHP, you can just put an extra $
in front of a variable to make it a dynamic variable :
$$variableName = $value;
While I wouldn't recommend it, you could even chain this behavior :
$$$$$$$$DoNotTryThisAtHomeKids = $value;
You can but are not forced to put $variableName
between {}
:
${$variableName} = $value;
Using {}
is only mandatory when the name of your variable is itself a composition of multiple values, like this :
${$variableNamePart1 . $variableNamePart2} = $value;
It is nevertheless recommended to always use {}
, because it's more readable.
Another reason to always use {}
, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.
In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.
$$foo['bar']['baz']
${$foo['bar']['baz']}
${$foo}['bar']['baz']
$foo->$bar['baz']
$foo->{$bar['baz']}
$foo->{$bar}['baz']
$foo->$bar['baz']()
$foo->{$bar['baz']}()
$foo->{$bar}['baz']()
Foo::$bar['baz']()
Foo::{$bar['baz']}()
Foo::{$bar}['baz']()
EDIT: to convert to array
int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();
This should do the trick:
var asIntegers = arr.Select(s => int.Parse(s));
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
I had the same issue but when i deleted the cached items from Temp folder the build failed.
In order to make the build work again I had to close the project and reopen it.
I had this problem and it went away when I moved from ADO.Net to Dapper for my queries.
Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed
var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
var td = $('<td>').append(test).appendTo(tr);
});
I prefer to create queries with SQLAlchemy, and then make a DataFrame from it. SQLAlchemy makes it easier to combine SQL conditions Pythonically if you intend to mix and match things over and over.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pandas import DataFrame
import datetime
# We are connecting to an existing service
engine = create_engine('dialect://user:pwd@host:port/db', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
# And we want to query an existing table
tablename = Table('tablename',
Base.metadata,
autoload=True,
autoload_with=engine,
schema='ownername')
# These are the "Where" parameters, but I could as easily
# create joins and limit results
us = tablename.c.country_code.in_(['US','MX'])
dc = tablename.c.locn_name.like('%DC%')
dt = tablename.c.arr_date >= datetime.date.today() # Give me convenience or...
q = session.query(tablename).\
filter(us & dc & dt) # That's where the magic happens!!!
def querydb(query):
"""
Function to execute query and return DataFrame.
"""
df = DataFrame(query.all());
df.columns = [x['name'] for x in query.column_descriptions]
return df
querydb(q)
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
In addition to the link provided by Floremin, which clears text selection using JavaScript to "clear" the selection, you can also use pure CSS to accomplish this. The CSS is here...
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Simply add the class="noSelect"
attribute to the element you wish to apply this class to. I would highly recommend giving this CSS solution a try. Nothing wrong with using the JavaScript, I just believe this could potentially be easier, and clean things up a little bit in your code.
For chrome on android
-webkit-tap-highlight-color: transparent;
is an additional rule you may want to experiment with for support in Android.
I faced the same issue and found it was due to zookeeper cluster nodes needs ports opened to communicate with each other.
server.1=xx.xx.xx.xx:2888:3888
server.2=xx.xx.xx.xx:2888:3888
server.3=xx.xx.xx.xx:2888:3888
once i allowed these ports through aws security group and restarted. All worked fine for me
To set a origins remote url-
git remote set-url origin git://new.url.here
here origin is your push url name. You may have multiple origin. If you have multiple origin replace origin as that name.
For deleting Origin
git remote rm origin/originName
or
git remote remove origin/originName
For adding new origin
git remote add origin/originName git://new.url.here / RemoteUrl
I have try this my new code and it might be helpful to you, it works perfectly in google chromr
hr {
color: #f00;
background: #f00;
width: 75%;
height: 5px;
}
You have to use the change
event on the input itself if you want to respond to manual input, because the changeDate
event is only for when the date is changed using the datepicker.
Try something like this:
$(document).ready(function() {
$('.datepicker').datepicker({
format: "yyyy-mm-dd",
})
//Listen for the change even on the input
.change(dateChanged)
.on('changeDate', dateChanged);
});
function dateChanged(ev) {
$(this).datepicker('hide');
if ($('#startdate').val() != '' && $('#enddate').val() != '') {
$('#period').text(diffInDays() + ' d.');
} else {
$('#period').text("-");
}
}
Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):
$('.navlink[data-selected="true"]');
or, better (for performance):
$('.navlink').filter('[data-selected="true"]');
or, if you want to get all the elements with data-selected
set:
$('[data-selected]')
Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data()
call, this method will no longer work.
To make it work in JSON, you need to escape a few more character than that.
myString.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\r", "\\r")
.replace("\n", "\\n")
and if you want to be able to use json2.js
to parse it then you also need to escape
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
which JSON allows inside quoted strings, but which JavaScript does not.
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() < 2 ) return true;
if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
return isPalindrome(in.substring(1,in.length-2));
else
return false;
}
Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.
If you are using npm test
(using package.json scripts) use an extra --
to pass the param through to mocha
e.g. npm test -- --grep "my second test"
EDIT: Looks like --grep
can be a little fussy (probably depending on the other arguments). You can:
Modify the package.json:
"test:mocha": "mocha --grep \"<DealsList />\" .",
Or alternatively use --bail
which seems to be less fussy
npm test -- --bail
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
You can use arg(), as follow:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
This is in deed due to characters messing around with the data. Using htmlentities($yourText)
worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities.
I had a similar problem while trying to add a variable to an object returned from an API. I was iterating through the data with a foreach loop.
foreach ( $results as $data ) {
$data->direction = 0;
}
This threw the "Creating default object from empty value" Exception in Laravel.
I fixed it with a very small change.
foreach ( $results as &$data ) {
$data->direction = 0;
}
By simply making $data a reference.
I hope that helps somebody a it was annoying the hell out of me!
Go to
Here are the docs about the "new" format syntax. An example would be:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals
and penalties
are integers (i.e. their default format is ok), it could be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since the parameters are fields of self
, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Explaining:
{}
means just the next positional argument, with default format;{0}
means the argument with index 0
, with default format;{:d}
is the next positional argument, with decimal integer format;{0:d}
is the argument with index 0
, with decimal integer format.There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)
"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)
"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'
"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'
"games: {:>3}".format(player1.games) # 'games: 123'
"games: {:>3}".format(player2.games) # 'games: 4'
"games: {:0>3}".format(player2.games) # 'games: 004'
Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).
Your solution is ok. only try it in this way:
files=$(grep -rl oldstr path) && echo $files | xargs sed....
so execute the xargs
only when grep return 0
, e.g. when found the string in some files.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
After lots of trial i found [a-zA-Z\\s]*
for Alphanumeric with white space
Example:
New York
New Delhi
First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript
If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:
$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
This will send the post variables to the specified url, and what the page returns will be in $response.
In your Activity
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@null"
android:hint="Text Example"
android:padding="5dp"
android:singleLine="true"
android:id="@+id/name"
android:textColor="@color/magenta"/>
Here is example using xargs
:
$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file
x86 is for a 32-bit OS, and x64 is for a 64-bit OS
Quoting from Conda: Myths and Misconceptions (a comprehensive description):
...
Reality: Conda and pip serve different purposes, and only directly compete in a small subset of tasks: namely installing Python packages in isolated environments.
Pip, which stands for Pip Installs Packages, is Python's officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI). Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).
In short, pip is a general-purpose manager for Python packages; conda is a language-agnostic cross-platform environment manager. For the user, the most salient distinction is probably this: pip installs python packages within any environment; conda installs any package within conda environments. If all you are doing is installing Python packages within an isolated environment, conda and pip+virtualenv are mostly interchangeable, modulo some difference in dependency handling and package availability. By isolated environment I mean a conda-env or virtualenv, in which you can install packages without modifying your system Python installation.
Even setting aside Myth #2, if we focus on just installation of Python packages, conda and pip serve different audiences and different purposes. If you want to, say, manage Python packages within an existing system Python installation, conda can't help you: by design, it can only install packages within conda environments. If you want to, say, work with the many Python packages which rely on external dependencies (NumPy, SciPy, and Matplotlib are common examples), while tracking those dependencies in a meaningful way, pip can't help you: by design, it manages Python packages and only Python packages.
Conda and pip are not competitors, but rather tools focused on different groups of users and patterns of use.
never forget to add @Entity on domain class
Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.
If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.
this is how i did it
TabLayout.xml
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="@android:color/transparent"
app:tabGravity="fill"
app:tabMode="scrollable"
app:tabTextAppearance="@style/TextAppearance.Design.Tab"
app:tabSelectedTextColor="@color/myPrimaryColor"
app:tabIndicatorColor="@color/myPrimaryColor"
android:overScrollMode="never"
/>
Oncreate
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mTabLayout = (TabLayout)findViewById(R.id.tab_layout);
mTabLayout.setOnTabSelectedListener(this);
setSupportActionBar(mToolbar);
mTabLayout.addTab(mTabLayout.newTab().setText("Dashboard"));
mTabLayout.addTab(mTabLayout.newTab().setText("Signature"));
mTabLayout.addTab(mTabLayout.newTab().setText("Booking/Sampling"));
mTabLayout.addTab(mTabLayout.newTab().setText("Calendar"));
mTabLayout.addTab(mTabLayout.newTab().setText("Customer Detail"));
mTabLayout.post(mTabLayout_config);
}
Runnable mTabLayout_config = new Runnable()
{
@Override
public void run()
{
if(mTabLayout.getWidth() < MainActivity.this.getResources().getDisplayMetrics().widthPixels)
{
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
ViewGroup.LayoutParams mParams = mTabLayout.getLayoutParams();
mParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
mTabLayout.setLayoutParams(mParams);
}
else
{
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
}
};
I made small changes of @Mario Velasco's solution on the runnable part
You need the public key in your gpg key ring. To import the public key into your public keyring, place the public key block in a text file with a .gpg extension, and then issue the following command:
gpg --import <your-file>.gpg
The entity that encrypted the file should provide you with such a block. For example, ftp://ftp.gnu.org/gnu/gnu-keyring.gpg has the block for gnu.org.
For an even more in-depth explanation see Verifying files with GPG, without a .sig or .asc file?
HTML
<table cellspacing="0">
<tr class="top bottom row">
<td>one one</td>
<td>one two</td>
</tr>
<tr class="top bottom row">
<td>two one</td>
<td>two two</td>
</tr>
<tr class="top bottom row">
<td>three one</td>
<td>three two</td>
</tr>
</table>?
CSS:
tr.top td { border-top: thin solid black; }
tr.bottom td { border-bottom: thin solid black; }
tr.row td:first-child { border-left: thin solid black; }
tr.row td:last-child { border-right: thin solid black; }?
Is it possible that you are using GCC 5?
If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you will need to recompile your code with the old ABI.
Source: GCC 5 Release Notes/Dual ABI
Defining the following macro before including any standard library headers should fix your problem: #define _GLIBCXX_USE_CXX11_ABI 0
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
I have used this in the past:
html
January<span class="right">2014</span>
Css
.right {
margin-left:100%;
}
You can use valueOf("a1")
if you want to look up by String
snippet to retrieve json data, password protected
import requests
username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"
session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
data={
'username': username,
'password': password,
'csrfmiddlewaretoken': csrf_token,
'next': the_page_i_want,
},
headers=dict(Referer=url+"/login"))
print(resp.json())
got this from cloud service documentation
pip install --upgrade google-cloud-translate
Worked for me !
Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/
$('#myform').on('change', 'input[type=checkbox]', function(e) {
console.log(this.name+' '+this.value+' '+this.checked);
});
Append the following statement to the JDBC-mysql protocol:
?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8
for example:
jdbc:mysql://localhost/infra?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
There is a property for this called keyboardType
.
What you'll want to do is replace where you have strings @"Number Pad
and @"Default
with UIKeyboardTypeNumberPad
and UIKeyboardTypeDefault
.
Your new code should look something like this:
if(user is prompted for numeric input only)
[textField setKeyboardType:UIKeyboardTypeNumberPad];
else if(user is prompted for alphanumeric input)
[textField setKeyboardType:UIKeyboardTypeDefault];
Good Luck!
if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.
html {
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
#fullHeight{
width: 450px;
**min-height: 100%;**
background-color: blue;
}
If you want the actual strings themselves to mutate in place (possibly and desirably affecting other references to the same string objects):
# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |_,str| str.gsub! /^|$/, '%' }
my_hash.each{ |_,str| str.replace "%#{str}%" }
If you want the hash to change in place, but you don't want to affect the strings (you want it to get new strings):
# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |key,str| my_hash[key] = "%#{str}%" }
my_hash.inject(my_hash){ |h,(k,str)| h[k]="%#{str}%"; h }
If you want a new hash:
# Ruby 1.8.6+
new_hash = Hash[*my_hash.map{|k,str| [k,"%#{str}%"] }.flatten]
# Ruby 1.8.7+
new_hash = Hash[my_hash.map{|k,str| [k,"%#{str}%"] } ]
How to do it with Oracle SQL Developer: In the Left pane, under the connections you will find "Sequences", right click and select create a new sequence from the context sensitive pop up. Fill out the details: Schema name, sequence_name, properties(start with value, min value, max value, increment value etc.) and click ok. Assuming that you have a table with a key that uses this auto_increment, while inserting in this table just give "your_sequence_name.nextval" in the field that utilizes this property. I guess this should help! :)
Something like the following would be my choice:
let selectElement = document.getElementById('categorySelect');
let selectedOptions = selectedElement.selectedOptions || [].filter.call(selectedElement.options, option => option.selected);
let selectedValues = [].map.call(selectedOptions, option => option.value);
It's short, it's fast on modern browsers, and we don't care whether it's fast or not on 1% market share browsers.
Note, selectedOptions has wonky behavior on some browsers from around 5 years ago, so a user agent sniff isn't totally out of line here.
Here's my solution. It's very simple. The frame scheduling could be better.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Image Refresh</title>
</head>
<body>
<!-- Get the initial image. -->
<img id="frame" src="frame.jpg">
<script>
// Use an off-screen image to load the next frame.
var img = new Image();
// When it is loaded...
img.addEventListener("load", function() {
// Set the on-screen image to the same source. This should be instant because
// it is already loaded.
document.getElementById("frame").src = img.src;
// Schedule loading the next frame.
setTimeout(function() {
img.src = "frame.jpg?" + (new Date).getTime();
}, 1000/15); // 15 FPS (more or less)
})
// Start the loading process.
img.src = "frame.jpg?" + (new Date).getTime();
</script>
</body>
</html>
I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.
Model:
public class MyViewModel
{
[PlaceHolder("Enter title here")]
public string Title { get; set; }
}
Html helper extension:
public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var metadata = modelMetadata;
var viewData = new
{
HtmlAttributes = new
{
@class = htmlClass,
placeholder = metadata.Watermark,
}
};
return htmlHelper.EditorFor(expression, viewData);
}
A corresponding view:
@Html.BsEditorFor(x => x.Title)
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
use desc tablename
from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.
$ hive -e 'desc dbname.tablename;' > ~/columnnames.txt
where dbname
is the name of the Hive database where your table is residing
You can find the file columnnames.txt in your root directory.
$cd ~
$ls
How about this if you want to compute the prime directly:
def oprime(n):
counter = 0
b = 1
if n == 1:
print 2
while counter < n-1:
b = b + 2
for a in range(2,b):
if b % a == 0:
break
else:
counter = counter + 1
if counter == n-1:
print b
This worked for me. Although i'm curious of the reason I started getting the errors in the first place. When I logged out yesterday, it was fine. Log in this morning, it wasn't.
rm .git/index
git reset
I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.
if((isset($_POST['name'])) && !empty($_POST['name']))
{
$name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
echo $name;
}
According to the grammar in the CSP spec, you need to specify schemes as scheme:
, not just scheme
. So, you need to change the image source directive to:
img-src 'self' data:;
I found that there was a syntax error in the related module and it wasn't compiling - the compiler didn't tell me that though. Just gave me the error regarding the app.config stuff. VS2010. Once I had fixed the syntax error, all was good.
Note that ≪Copy all as HAR≫ does not contain response body.
You can get response body via ≪Save as HAR with Content≫, but it breaks if you have any more than a trivial amount of logs (I tried once with only 8k requests and it doesn't work.) To solve this, you can script an output yourself using _request.contentData()
.
When there's too many logs, even _request.contentData()
and ≪Copy response≫ would fail, hopefully they would fix this problem. Until then, inspecting any more than a trivial amount of network logs cannot be properly done with Chrome Network Inspector and its best to use another tool.
function calculateExamRemainingTime(exam_end_at) {
$(function(){
const calcNewYear = setInterval(function(){
const exam_ending_at = new Date(exam_end_at);
const current_time = new Date();
const totalSeconds = Math.floor((exam_ending_at - (current_time))/1000);;
const totalMinutes = Math.floor(totalSeconds/60);
const totalHours = Math.floor(totalMinutes/60);
const totalDays = Math.floor(totalHours/24);
const hours = totalHours - ( totalDays * 24 );
const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );
const examRemainingHoursSection = document.querySelector('#remainingHours');
const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
const examRemainingSecondsSection = document.querySelector('#remainingSeconds');
examRemainingHoursSection.innerHTML = hours.toString();
examRemainingMinutesSection.innerHTML = minutes.toString();
examRemainingSecondsSection.innerHTML = seconds.toString();
},1000);
});
}
calculateExamRemainingTime('2025-06-03 20:20:20');
A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
How about this?
for item in mylist:
if item in checklist:
pass
else:
# do something
print item
in my case, creating an empty column and setting its accessor worked fine. my accessor filling user's age from dob column. toArray() function worked too.
public function getAgeAttribute()
{
return Carbon::createFromFormat('Y-m-d', $this->attributes['dateofbirth'])->age;
}
For anyone still looking at this querstion. This is for a hyperlink but you can modify it for just a plain underline:
Create a drawable (hyperlink_underline.xml):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="-10dp"
android:left="-10dp"
android:right="-10dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<stroke android:width="2dp"
android:color="#3498db"/>
</shape>
</item>
</layer-list>
Create a new style:
<style name="Hyperlink">
<item name="android:textColor">#3498db</item>
<item name="android:background">@drawable/hyperlink_underline</item>
</style>
Then use this style on your TextView:
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
local:MvxBind="Text Id; Click ShowJobInfoCommand"
style="@style/HyperLink"/>
You may append HTML <br />
in between your lines. Something like:
MyLabel.Text = "SomeText asdfa asd fas df asdf" + "<br />" + "Some more text";
With StringBuilder you can try:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />");
We use a series of static methods to pull all of the values out of our data readers. So in this case we'd be calling DBUtils.GetString(sqlreader(indexFirstName))
The benefit of creating static/shared methods is that you don't have to do the same checks over and over and over...
The static method(s) would contain code to check for nulls (see other answers on this page).
$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);
I use this Bash script to test the internet status every minute on OSX
#address=192.168.1.99 # forced bad address for testing/debugging
address=23.208.224.170 # www.cisco.com
internet=1 # default to internet is up
while true;
do
# %a Day of Week, textual
# %b Month, textual, abbreviated
# %d Day, numeric
# %r Timestamp AM/PM
echo -n $(date +"%a, %b %d, %r") "-- "
ping -c 1 ${address} > /tmp/ping.$
if [[ $? -ne 0 ]]; then
if [[ ${internet} -eq 1 ]]; then # edge trigger -- was up now down
echo -n $(say "Internet down") # OSX Text-to-Speech
echo -n "Internet DOWN"
else
echo -n "... still down"
fi
internet=0
else
if [[ ${internet} -eq 0 ]]; then # edge trigger -- was down now up
echo -n $(say "Internet back up") # OSX Text-To-Speech
fi
internet=1
fi
cat /tmp/ping.$ | head -2 | tail -1
sleep 60 ; # sleep 60 seconds =1 min
done
This is not the most performant solution, but as somebody suggested instead of background you can create FrameLayout or RelativeLayout and use ImageView as pseudo background - other elements will be position simply above it:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ImageView
android:id="@+id/ivBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitStart"
android:src="@drawable/menu_icon_exit" />
<Button
android:id="@+id/bSomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="61dp"
android:layout_marginTop="122dp"
android:text="Button" />
</RelativeLayout>
The problem with ImageView is that only scaleTypes available are: CENTER, CENTER_CROP, CENTER_INSIDE, FIT_CENTER,FIT_END, FIT_START, FIT_XY, MATRIX (http://etcodehome.blogspot.de/2011/05/android-imageview-scaletype-samples.html)
and to "scale the background image (keeping its aspect ratio)" in some cases, when you want an image to fill the whole screen (for example background image) and aspect ratio of the screen is different than image's, the necessary scaleType is kind of TOP_CROP, because:
CENTER_CROP centers the scaled image instead of aligning the top edge to the top edge of the image view and FIT_START fits the screen height and not fill the width. And as user Anke noticed FIT_XY doesn't keep aspect ratio.
Gladly somebody has extended ImageView to support TOP_CROP
public class ImageViewScaleTypeTopCrop extends ImageView {
public ImageViewScaleTypeTopCrop(Context context) {
super(context);
setup();
}
public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public ImageViewScaleTypeTopCrop(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
@Override
protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
if (getDrawable() != null) {
Matrix matrix = getImageMatrix();
float scaleFactor, scaleFactorWidth, scaleFactorHeight;
scaleFactorWidth = (float) frameWidth / (float) getDrawable().getIntrinsicWidth();
scaleFactorHeight = (float) frameHeight / (float) getDrawable().getIntrinsicHeight();
if (scaleFactorHeight > scaleFactorWidth) {
scaleFactor = scaleFactorHeight;
} else {
scaleFactor = scaleFactorWidth;
}
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
}
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
https://stackoverflow.com/a/14815588/2075875
Now IMHO would be perfect if somebody wrote custom Drawable which scales image like that. Then it could be used as background parameter.
Reflog suggests to prescale drawable before using it. Here is instruction how to do it: Java (Android): How to scale a drawable without Bitmap? Although it has disadvantage, that upscaled drawable/bitmap will use more RAM, while scaling on the fly used by ImageView doesn't require more memory. Advantage could be less processor load.
You can also , have an observable which triggers on changes in the parent component(CategoryComponent)
and do what you want to do in the subscribtion in the child component. (videoListComponent
)
service.ts
public categoryChange$ : ReplaySubject<any> = new ReplaySubject(1);
CategoryComponent.ts
public onCategoryChange(): void {
service.categoryChange$.next();
}
videoListComponent.ts
public ngOnInit(): void {
service.categoryChange$.subscribe(() => {
// do your logic
});
}
Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.
Original script was
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
V_ERROR_NAME varchar2(200) := '';
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
Rewritten the same without global variable V_ERROR_NAME
and moved to procedure under package level as
Modified Code
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS
**V_ERROR_NAME varchar2(200) := '';**
BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
One way:
import os
os.listdir("/home/username/www/")
glob.glob("/home/username/www/*")
The glob.glob
method above will not list hidden files.
Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir
method on Path
objects:
from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
Here's my solution using PycURL and validators
import pycurl, validators
def url_exists(url):
"""
Check if the given URL really exists
:param url: str
:return: bool
"""
if validators.url(url):
c = pycurl.Curl()
c.setopt(pycurl.NOBODY, True)
c.setopt(pycurl.FOLLOWLOCATION, False)
c.setopt(pycurl.CONNECTTIMEOUT, 10)
c.setopt(pycurl.TIMEOUT, 10)
c.setopt(pycurl.COOKIEFILE, '')
c.setopt(pycurl.URL, url)
try:
c.perform()
response_code = c.getinfo(pycurl.RESPONSE_CODE)
c.close()
return True if response_code < 400 else False
except pycurl.error as err:
errno, errstr = err
raise OSError('An error occurred: {}'.format(errstr))
else:
raise ValueError('"{}" is not a valid url'.format(url))
tracking branch is nothing but a way to save us some typing.
If we track a branch, we do not have to always type git push origin <branch-name>
or git pull origin <branch-name>
or git fetch origin <branch-name>
or git merge origin <branch-name>
. given we named our remote origin
, we can just use git push
, git pull
, git fetch
,git merge
, respectively.
We track a branch when we:
git clone
git push -u origin <branch-name>
. This -u
make it a tracking branch.git branch -u origin/branch_name branch_name
To say "nodemon" would answer the question.
But on how only to kill (all) node demon(s), the following works for me:
pkill -HUP node
Lots of good advince in the other posts. This is what I use:
Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();
If you need another randomness provider, which I sometime do for testing purposes, just replace rand with
MySecureRandom rand = new MySecureRandom();
I came across this post even though I needed to SHRINKFILE on MSSQL 2012 version which is little trickier since 2000 or 2005 versions. After reading up on all risks and issues related to this issue I ended up testing. Long story short, the best results I got were from using the MS SQL Server Management Studio.
Right-Click the DB -> TASKS -> SHRINK -> FILES -> select the LOG file
for Specific table you cannot use $this->db->insert_id() . even the last insert happened long ago it can be fetched like this. may be wrong. but working well for me
$this->db->select_max('{primary key}');
$result= $this->db->get('{table}')->row_array();
echo $result['{primary key}'];
Add the following css to disable the default scroll:
body {
overflow: hidden;
}
And change the #content
css to this to make the scroll only on content body:
#content {
max-height: calc(100% - 120px);
overflow-y: scroll;
padding: 0px 10%;
margin-top: 60px;
}
Edit:
Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
bottom: 30px;_x000D_
right: 0;_x000D_
left: 0;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
background-color: #4C4;_x000D_
height: 50px;_x000D_
}_x000D_
footer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #4C4;_x000D_
height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
How about less /var/log/syslog
?
Avoid using Xcode to rename files in a folder reference. If you rename a file using Xcode, it will be marked for commit. If you later delete it before the commit, you will end up with this error.
I think using react-native-responsive-dimensions
might help you a little better on your case.
You can still get:
device-width by using and responsiveScreenWidth(100)
and
device-height by using and responsiveScreenHeight(100)
You also can more easily arrange the locations of your absolute components by setting margins and position values with proportioning it over 100% of the width and height
.pdflink:after {
background-image: url('/images/pdf.png');
background-size: 10px 20px;
width: 10px;
height: 20px;
padding-left: 10px;// equal to width of image.
margin-left:5px;// to add some space for better look
content:"";
}
Okay, this option is pretty hackish but should work.
$(document).ready( function() {
$('#select').change( function() {
$('#hiddenDiv').html( $('#select').val() );
$('#select').width( $('#hiddenDiv').width() );
}
}
Which would offcourse require a hidden div.
<div id="hiddenDiv" style="visibility:hidden"></div>
ohh and you will need jQuery
You don't need align="center"
and float:left
. Remove both of these. margin: 0 auto
is sufficient.
Use git ls-remote git://github.com/<user>/<project>.git
. For example, my trac-backlog project gives:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0 HEAD
4652257768acef90b9af560295b02d0ac6e7702c refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3 refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0 refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1 refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2 refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400 refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726 refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24 refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3 refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69 refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5 refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125 refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1 refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708 refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57 refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070 refs/tags/0.3.0^{}
Just grep for the one you need and cut it out:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0
Or, you can specify which refs you want on the command line and avoid the grep with:
:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0
Note: it doesn't have to be the git://
URL. It could be https://
or [email protected]:
too.
Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:
git rev-parse branch-name
It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:
git rev-parse HEAD
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
You can't really do this unless you build them yourself in an ng-repeat.
<select ng-model="foo">
<option ng-repeat="item in items" value="{{item.code}}">{{item.name}}</option>
</select>
BUT... it's probably not worth it. It's better to leave it function as designed and let Angular handle the inner workings. Angular uses the index this way so you can actually use an entire object as a value. So you can use a drop down binding to select a whole value rather than just a string, which is pretty awesome:
<select ng-model="foo" ng-options="item as item.name for item in items"></select>
{{foo | json}}
Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule
.
You can load a DataTable
directly from a data reader using the Load()
method that accepts an IDataReader
.
var dataReader = cmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
From Git Bash I prefer to run the command:
git config --global credential.helper wincred
At that point running a command like git pull
and entering your credentials one time should have it stored for future use. Git has a built-in credentials system that works in different OS environments. You can get more details here: 7.14 Git Tools - Credential Storage
== ISSUE THIS COMMAND
[xxx@devxxx ~]$ screen -ls
== SCREEN RESPONDS
There are screens on:
23487.pts-0.devxxx (Detached)
26727.pts-0.devxxx (Attached)
2 Sockets in /tmp/uscreens/S-xxx.
== NOW KILL THE ONE YOU DONT WANT
[xxx@devxxx ~]$ screen -X -S 23487.pts-0.devxxx kill
== WANT PROOF?
[xxx@devxxx ~]$ screen -ls
There is a screen on:
26727.pts-0.devxxx (Attached)
1 Socket in /tmp/uscreens/S-xxx.
I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.
In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0)
returns 1
thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0)
returns 0
thus making the code return:
string = [string substringToIndex:string.length-0];
Which prevents crashes.
this version will work in all the latest browsers and ie8 if you have the modernizr script (if not just change header
and footer
into div
s):
html,_x000D_
body {_x000D_
min-height: 100%;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
padding: 50px 0;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
#content {_x000D_
min-height: 100%;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
header {_x000D_
margin-top: -50px;_x000D_
height: 50px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
footer {_x000D_
margin-bottom: -50px;_x000D_
height: 50px;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
p {_x000D_
margin: 0;_x000D_
padding: 0 0 1em 0;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<header>dfs</header>_x000D_
<div id="content">_x000D_
</div>_x000D_
<footer>sdf</footer>_x000D_
</div>
_x000D_
Scrolling with content: Fiddle