I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0
and the compiled .so file is under the build folder.
you can type python setup.py --help build_ext
to see the explanations of -R and -I
Based on my personal experience with this knowledge base software, I would also like to join 'Julien H.' in suggesting PHPKB from http://www.knowledgebase-script.com
Personally I believe its one of the best. Many features, continously developed, excellent support & the GUI is just simple & great.
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
You can create a new table using the following code.
SELECT IDENTITY (int, 1, 1) AS id, column1, column2
INTO dbo.NewTable
FROM dbo.OldTable
Then delete the old db, and rename the new db to the old db's name. Note: that column1 and column2 represent all the columns in your old table that you want to keep in your new table.
ListViewItem item = new ListViewItem();
item.Text = "fdfdfd";
item.SubItems.Add ("melp");
listView.Items.Add(item);
The following code creates and prints an array of strings in shell:
#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
echo "$element"
done
echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"
Result:
A
B
ElementC
ElementE
Number of elements: 4
A B ElementC ElementE
In a past project that had to support IE8+ and I achieved this using a image encoded in data-url format.
The image was 2800x1px, half of the image white, and half transparent. Worked pretty well.
body {
/* 50% right white */
background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAOSURBVHgBYxhi4P/QAgDwrK5SDPAOUwAAAABJRU5ErkJggg==) center top repeat-y;
/* 50% left white */
background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAPSURBVHgBY/g/tADD0AIAIROuUgYu7kEAAAAASUVORK5CYII=) center top repeat-y;
}
You can see it working here JsFiddle. Hope it can help someone ;)
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();
You might have output (maybe error/debug output) that precedes your call to
header("Content-type: text/xml");
Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
I use frame and expand option. Very simple. I want some buttons in the middle of screen. Resize window and button stay in the middle. This is my solution.
frame = Frame(parent_window)
Button(frame, text='button1', command=command_1).pack(fill=X)
Button(frame, text='button2', command=command_2).pack(fill=X)
Button(frame, text='button3', command=command_3).pack(fill=X)
frame.pack(anchor=CENTER, expand=1)
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
I also faced the similar issues, changing the version from 2.0.0.RELEASE to 1.5.10.RELEASE worked for me, please try it before downgrading the maven version
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
this worked for me:-
<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>
thanks for sharing code...
Array
(
[__ci_last_regenerate] => 1490879962
[user_id] => 3
[designation_name] => Admin
[region_name] => admin
[territory_name] => admin
[designation_id] => 2
[region_id] => 1
[territory_id] => 1
[employee_user_id] => mosin11
)
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u
means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u
in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.
You can create a Unicode string multiple ways:
>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'
But the real reason is to represent something like this (translation here):
>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????
For the most part, Unicode and non-Unicode strings are interoperable on Python 2.
There are other symbols you will see, such as the "raw" symbol r
for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.
>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'
Unicode and non-Unicode strings can be equal on Python 2:
>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True
but not on Python 3:
>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False
I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break
statement:
finished = False
while not finished:
... do something...
finished = evaluate_end_condition()
I believe the simplest method would be to use Python:
python -m webbrowser "http://www.example.com/"
If you run in linux, open file netbeans.conf using nano or anything else.
nano netbeans-8.2/etc/netbeans.conf
and edit jdkhome or directory for jdk
netbeans_jdkhome="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
you can check your jdk version with
java -version
or
ls /usr/lib/jvm
Just use ng-repeat="(sectionIndex, section) in sections"
and that will be useable on the next level ng-repeat down.
<ul ng-repeat="(sectionIndex, section) in sections">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}, Your section index is {{sectionIndex}}
</li>
</ul>
</ul>
You can also count on multiple groups and their intersection:
self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()
The query above will return counts for all possible combinations of values from both columns.
Look at real_ates
ES2016 way, it's more correct.
import crypto from 'crypto';
function spawnTokenBuf() {
return function(callback) {
crypto.randomBytes(48, callback);
};
}
async function() {
console.log((await spawnTokenBuf()).toString('base64'));
};
var crypto = require('crypto');
var co = require('co');
function spawnTokenBuf() {
return function(callback) {
crypto.randomBytes(48, callback);
};
}
co(function* () {
console.log((yield spawnTokenBuf()).toString('base64'));
});
This script detects all versions of Firefox, for Desktop, from version 1 to 46.
It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.
I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
// Match UserAgent string with Firefox Desktop_x000D_
// Detect hybrid Gecko browsers and mobile_x000D_
if (navigator.userAgent.match(/firefox/i) &&_x000D_
!navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
// Create Element and Array to test availability _x000D_
var createdElement = document.createElement('div'),_x000D_
createdArray = [],_x000D_
firefoxVersion = "0";_x000D_
_x000D_
// Firefox 1.0 released November 9, 2004 _x000D_
// Check a current feature as being true, or NOT undefined _x000D_
// AND check future features as EQUAL undefined_x000D_
if (typeof window.alert !== "undefined" &&_x000D_
typeof window.XPCNativeWrapper === "undefined" &&_x000D_
typeof window.URL === "undefined") {_x000D_
firefoxVersion = "1";_x000D_
}_x000D_
_x000D_
// Firefox 1.5 released October 15, 2003 _x000D_
// XPCNativeWrapper used to create security wrapper_x000D_
else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
typeof window.globalStorage === "undefined" &&_x000D_
typeof window.devicePixelRatio === "undefined" &&_x000D_
typeof createdElement.style.animation === "undefined" &&_x000D_
typeof document.querySelector === "undefined") {_x000D_
firefoxVersion = "1.5";_x000D_
}_x000D_
_x000D_
// Firefox 2 released October 24, 2006_x000D_
// globalStorage later deprecated in favor of localstorage_x000D_
else if (typeof window.globalStorage !== "undefined" &&_x000D_
typeof window.postMessage === "undefined") {_x000D_
firefoxVersion = "2";_x000D_
}_x000D_
_x000D_
// Firefox 3 released June 17, 2008_x000D_
// postMessage for cross window messaging_x000D_
else if (typeof window.postMessage !== "undefined" &&_x000D_
typeof document.querySelector === "undefined") {_x000D_
firefoxVersion = "3";_x000D_
}_x000D_
_x000D_
// Firefox 3.5 released June 30, 2009_x000D_
// querySelector returns list of the elements from document_x000D_
else if (typeof document.querySelector !== "undefined" &&_x000D_
typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
typeof Reflect === "undefined") {_x000D_
firefoxVersion = "3.5";_x000D_
}_x000D_
_x000D_
// Firefox 4 released March 22, 2011_x000D_
// window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
else if (typeof window.URL !== "undefined" &&_x000D_
typeof createdElement.style.MozAnimation === "undefined") {_x000D_
firefoxVersion = "4";_x000D_
}_x000D_
_x000D_
// After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
// Firefox 5 released June 21, 2011_x000D_
// style.MozAnimation for CSS animation, renamed to style.animation_x000D_
else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
typeof WeakMap === "undefined") {_x000D_
firefoxVersion = "5";_x000D_
}_x000D_
_x000D_
// Firefox 6 released August 16, 2011_x000D_
// WeakMap collects key value pairs weakly referenced_x000D_
else if (typeof WeakMap !== "undefined" &&_x000D_
typeof createdElement.style.textOverflow === "undefined") {_x000D_
firefoxVersion = "6";_x000D_
}_x000D_
_x000D_
// Firefox 7 released September 27, 2011_x000D_
// textOverflow manages overflowed non displayed content_x000D_
else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
firefoxVersion = "7";_x000D_
}_x000D_
_x000D_
// Firefox 8 released November 8, 2011_x000D_
// insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
// faster than direct innerHTML manipulation and_x000D_
// appends without affecting other elements under the same parent_x000D_
else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
typeof navigator.doNotTrack === "undefined") {_x000D_
firefoxVersion = "8";_x000D_
}_x000D_
_x000D_
// Firefox 9 released December 20, 2011_x000D_
// mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
// IndexDB improved functionality than localstorage_x000D_
else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
typeof document.mozFullScreenEnabled === "undefined") {_x000D_
firefoxVersion = "9";_x000D_
}_x000D_
_x000D_
// Firefox 10 released January 31, 2012_x000D_
// mozFullScreenEnabled reports if full-screen mode is available_x000D_
else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
typeof Reflect === "undefined") {_x000D_
firefoxVersion = "10";_x000D_
}_x000D_
_x000D_
// Firefox 11 released March 13, 2012_x000D_
// mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
// Cancels an animation frame request_x000D_
else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
firefoxVersion = "11";_x000D_
}_x000D_
_x000D_
// Firefox 12 released April 24, 2012_x000D_
// MozTextAlignLast how the last line is aligned_x000D_
else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
firefoxVersion = "12";_x000D_
}_x000D_
_x000D_
// Firefox 13 released June 5, 2012_x000D_
// MozOpacity dropped from this version_x000D_
else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
typeof window.globalStorage !== "undefined") {_x000D_
firefoxVersion = "13";_x000D_
}_x000D_
_x000D_
// Firefox 14 released June 26, 2012_x000D_
// globalStorage dropped from this version_x000D_
else if (typeof window.globalStorage === "undefined" &&_x000D_
typeof createdElement.style.borderImage === "undefined" &&_x000D_
typeof document.querySelector !== "undefined") {_x000D_
firefoxVersion = "14";_x000D_
}_x000D_
_x000D_
// Firefox 15 released August 28, 2012_x000D_
// borderImage allows drawing an image on the borders of elements_x000D_
else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
typeof createdElement.style.animation === "undefined") {_x000D_
firefoxVersion = "15";_x000D_
}_x000D_
_x000D_
// Firefox 16 released October 9, 2012_x000D_
// animation was MozAnimation_x000D_
else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
typeof createdElement.style.iterator === "undefined" &&_x000D_
typeof Math.hypot === "undefined") {_x000D_
firefoxVersion = "16";_x000D_
}_x000D_
_x000D_
// Firefox 17 released November 20, 2012_x000D_
// version 27 drops iterator and renames italic_x000D_
// Used to iterate over enumerable properties of an object_x000D_
else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
typeof window.devicePixelRatio === "undefined") {_x000D_
firefoxVersion = "17";_x000D_
}_x000D_
_x000D_
// Firefox 18 released January 8, 2013_x000D_
// devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
typeof window.getInterface === "undefined" &&_x000D_
typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
firefoxVersion = "18";_x000D_
}_x000D_
_x000D_
// Firefox 19 released February 19, 2013_x000D_
// getInterface dropped and renamed in version 32_x000D_
// Retrieves specified interface pointers_x000D_
else if (typeof window.getInterface !== "undefined" &&_x000D_
typeof Math.imul === "undefined") {_x000D_
firefoxVersion = "19";_x000D_
}_x000D_
_x000D_
// Firefox 20 released April 2, 2013_x000D_
// Math.imul provides fast 32 bit integer multiplication_x000D_
else if (typeof Math.imul !== "undefined" &&_x000D_
typeof window.crypto.getRandomValues === "undefined") {_x000D_
firefoxVersion = "20";_x000D_
}_x000D_
_x000D_
// Firefox 21 released May 14, 2013_x000D_
// getRandomValues lets you get cryptographically random values_x000D_
else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
typeof createdElement.style.flex === "undefined") {_x000D_
firefoxVersion = "21";_x000D_
}_x000D_
_x000D_
// Firefox 22 released June 25, 2013_x000D_
// flex can alter dimensions to fill available space_x000D_
else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
typeof window.cancelAnimationFrame === "undefined") {_x000D_
firefoxVersion = "22";_x000D_
}_x000D_
_x000D_
// Firefox 23 released August 6, 2013_x000D_
// cancelAnimationFrame was mozCancelAnimationFrame_x000D_
else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
typeof document.loadBindingDocument !== "undefined" &&_x000D_
typeof Math.trunc === "undefined") {_x000D_
firefoxVersion = "23";_x000D_
}_x000D_
_x000D_
// Firefox 24 released September 17, 2013_x000D_
// loadBindingDocument dropped_x000D_
// loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
typeof Math.trunc === "undefined") {_x000D_
firefoxVersion = "24";_x000D_
}_x000D_
_x000D_
// Firefox 25 released October 29, 2013_x000D_
// Math.trunc returns number removing fractional digits_x000D_
else if (typeof Math.trunc !== "undefined" &&_x000D_
typeof document.loadBindingDocument !== "undefined") {_x000D_
firefoxVersion = "25";_x000D_
}_x000D_
_x000D_
// Firefox 26 released December 10, 2013_x000D_
// loadBindingDocument dropped_x000D_
else if (typeof Math.trunc !== "undefined" &&_x000D_
typeof Math.hypot === "undefined") {_x000D_
firefoxVersion = "26";_x000D_
}_x000D_
_x000D_
// Firefox 27 released February 4, 2014_x000D_
// Math.hypot returns square root of the sum of squares_x000D_
else if (typeof Math.hypot !== "undefined" &&_x000D_
typeof createdArray.entries === "undefined") {_x000D_
firefoxVersion = "27";_x000D_
}_x000D_
_x000D_
// Firefox 28 released March 18, 2014_x000D_
// entries returns key value pairs for arrays_x000D_
else if (typeof createdArray.entries !== "undefined" &&_x000D_
typeof createdElement.style.boxSizing === "undefined") {_x000D_
firefoxVersion = "28";_x000D_
}_x000D_
_x000D_
// Firefox 29 released April 29, 2014_x000D_
// boxSizing alters CSS box model, calculates width and height of elements_x000D_
else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
firefoxVersion = "29";_x000D_
}_x000D_
_x000D_
// Firefox 30 released June 10, 2014_x000D_
// backgroundBlendMode blends elements background images_x000D_
else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
typeof createdElement.style.paintOrder === "undefined") {_x000D_
firefoxVersion = "30";_x000D_
}_x000D_
_x000D_
// Firefox 31 released July 22, 2014_x000D_
// paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
firefoxVersion = "31";_x000D_
}_x000D_
_x000D_
// Firefox 32 released September 2, 2014_x000D_
// mixBlendMode how an element should blend _x000D_
else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
typeof Number.toInteger !== "undefined") {_x000D_
firefoxVersion = "32";_x000D_
}_x000D_
_x000D_
// Firefox 33 released October 14, 2014_x000D_
// numberToIntger dropped, used to convert values to integer_x000D_
else if (typeof Number.toInteger === "undefined" &&_x000D_
typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
firefoxVersion = "33";_x000D_
}_x000D_
_x000D_
// Firefox 34 released December 1, 2014_x000D_
// fontFeatureSettings control over advanced typographic features_x000D_
else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
firefoxVersion = "34";_x000D_
}_x000D_
_x000D_
// Firefox 35 released January 13, 2015_x000D_
// mozIsLocallyAvailable dropped_x000D_
else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
firefoxVersion = "35";_x000D_
}_x000D_
_x000D_
// Firefox 36 released February 24, 2015_x000D_
// quote returns a copy of the string_x000D_
else if (typeof String.quote !== "undefined" &&_x000D_
typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
firefoxVersion = "36";_x000D_
}_x000D_
_x000D_
// Firefox 37 released March 31, 2015_x000D_
// quote quickly dropped_x000D_
else if (typeof String.quote === "undefined" &&_x000D_
typeof createdElement.style.rubyPosition === "undefined") {_x000D_
firefoxVersion = "37";_x000D_
}_x000D_
_x000D_
// Firefox 38 released May 12, 2015_x000D_
// rubyPosition defines position of a ruby element relative to its base element_x000D_
else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
typeof window.Headers === "undefined") {_x000D_
firefoxVersion = "38";_x000D_
}_x000D_
_x000D_
// Firefox 39 released July 2, 2015_x000D_
// Headers allows us to create our own headers objects _x000D_
else if (typeof window.Headers !== "undefined" &&_x000D_
typeof Symbol.match === "undefined") {_x000D_
firefoxVersion = "39";_x000D_
}_x000D_
_x000D_
// Firefox 40 released August 11, 2015_x000D_
// match matches a regular expression against a string_x000D_
else if (typeof Symbol.match !== "undefined" &&_x000D_
typeof Symbol.species === "undefined") {_x000D_
firefoxVersion = "40";_x000D_
}_x000D_
_x000D_
// Firefox 41 released September 22, 2015_x000D_
// species allows subclasses to over ride the default constructor_x000D_
else if (typeof Symbol.species !== "undefined" &&_x000D_
typeof Reflect === "undefined") {_x000D_
firefoxVersion = "41";_x000D_
}_x000D_
_x000D_
// Firefox 42 released November 3, 2015_x000D_
// mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
// Reflect offers methods for interceptable JavaScript operations_x000D_
else if (typeof Reflect !== "undefined" &&_x000D_
typeof window.screen.orientation === "undefined") {_x000D_
firefoxVersion = "42";_x000D_
}_x000D_
_x000D_
// Firefox 43 released December 15, 2015_x000D_
// orientation is mozOrientation in B2G and Android_x000D_
else if (typeof window.screen.orientation !== "undefined" &&_x000D_
typeof document.charset === "undefined") {_x000D_
firefoxVersion = "43";_x000D_
}_x000D_
_x000D_
// Firefox 44 released January 26, 2016_x000D_
// charset is for legacy, use document.characterSet_x000D_
else if (typeof document.charset !== "undefined" &&_x000D_
typeof window.onstorage === "undefined") {_x000D_
firefoxVersion = "44";_x000D_
}_x000D_
_x000D_
// Firefox 45 released March 8, 2016_x000D_
// onstorage contains an event handler that runs when the storage event fires_x000D_
else if (typeof window.onstorage !== "undefined" &&_x000D_
typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
firefoxVersion = "45";_x000D_
}_x000D_
_x000D_
// Firefox 46 - beta_x000D_
// onabsolutedeviceorientation_x000D_
else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
firefoxVersion = "46 or above";_x000D_
}_x000D_
_x000D_
// Else could not verify_x000D_
else {_x000D_
outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
}_x000D_
_x000D_
// Display Firefox version_x000D_
outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
// Else not detected_x000D_
} else {_x000D_
outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
}_x000D_
} catch (e) {_x000D_
// Statement to handle exceptions_x000D_
outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
IMHO I think that all the models have a great place but the problem I have with the model first approach is in many large businesses with DBA's controlling the databases you do not get the flexibility of building applications without using database first approaches. I have worked on many projects and when it came to deployment they wanted full control.
So as much as I agree with all the possible variations Code First, Model First, Database first, you must consider the actual production environment. So if your system is going to be a large user base application with many users and DBA's running the show then you might consider the Database first option just my opinion.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s="";
while(scan.hasNext())
{
s=scan.nextLine();
}
System.out.println("String: " +s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.
event_id show_id event_name judge_id
0101 01 Dressage 01
0102 01 Jumping 02
0103 01 Led in 01
0201 02 Led in 02
0301 03 Led in 01
0401 04 Dressage 04
0501 05 Dressage 01
0502 05 Flag and Pole 02
Ans:
select event_name, count(show_id) as held_times from event
group by event_name
order by count(show_id) desc
If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).
For Print Result to text file
we can follow
echo "test data" > test.txt
This will create test.txt file and written "test data"
If you want to append then
echo "test data" >> test.txt
Following these steps allows you to install tensorflow and keras:
Download Anaconda3-5.2.0 which comes with python 3.6 from https://repo.anaconda.com/archive/
Install Anaconda and open Anaconda Prompt and execute below commands
conda install jupyter
conda install scipy
pip install sklearn
pip install msgpack
pip install pandas
pip install pandas-datareader
pip install matplotlib
pip install pillow
pip install requests
pip install h5py
pip install tensorflow
pip install keras
You can use twitter search page to bypass 3,200 limit. However you have to scroll down many times in the search results page. For example, I searched tweets from @beyinsiz_adam. This is the link of search results: https://twitter.com/search?q=from%3Abeyinsiz_adam&src=typd&f=realtime
Now in order to scroll down many times, you can use the following javascript code.
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
window.scrollTo(0,document.body.scrollHeight);
}
Just run it in the FireBug console. And wait some time to load all tweets.
Another java 8 lambda option :
String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);
And the ugly but optimized version without new array creation
Arrays.stream(array).map(String::trim).toArray(unused -> array);
Original "array" is modified.
if we make the particular activity
as
android:exported="true"
it will be the launching activity
.
Click on the module name just to the left of the run button
and click on "Edit configurations..." Now make sure "Launch default Activity"
is selected.
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
When you want monitor specified process, usually it is done by scripting. Here is perl example. This put percents as the same way as top, scalling it to one CPU. Then when some process is active working with 2 threads, cpu usage can be more than 100%. Specially look how cpu cores are counted :D then let me show my example:
#!/usr/bin/perl
my $pid=1234; #insert here monitored process PID
#returns current process time counters or single undef if unavailable
#returns: 1. process counter , 2. system counter , 3. total system cpu cores
sub GetCurrentLoads {
my $pid=shift;
my $fh;
my $line;
open $fh,'<',"/proc/$pid/stat" or return undef;
$line=<$fh>;
close $fh;
return undef unless $line=~/^\d+ \([^)]+\) \S \d+ \d+ \d+ \d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+)/;
my $TimeApp=$1+$2;
my $TimeSystem=0;
my $CpuCount=0;
open $fh,'<',"/proc/stat" or return undef;
while (defined($line=<$fh>)) {
if ($line=~/^cpu\s/) {
foreach my $nr ($line=~/\d+/g) { $TimeSystem+=$nr; };
next;
};
$CpuCount++ if $line=~/^cpu\d/;
}
close $fh;
return undef if $TimeSystem==0;
return $TimeApp,$TimeSystem,$CpuCount;
}
my ($currApp,$currSys,$lastApp,$lastSys,$cores);
while () {
($currApp,$currSys,$cores)=GetCurrentLoads($pid);
printf "Load is: %5.1f\%\n",($currApp-$lastApp)/($currSys-$lastSys)*$cores*100 if defined $currApp and defined $lastApp and defined $currSys and defined $lastSys;
($lastApp,$lastSys)=($currApp,$currSys);
sleep 1;
}
I hope it will help you in any monitoring. Of course you should use scanf or other C functions for converting any perl regexpes I've used to C source. Of course 1 second for sleeping is not mandatory. you can use any time. effect is, you will get averrage load on specfied time period. When you will use it for monitoring, of course last values you should put outside. It is needed, because monitoring usually calls scripts periodically, and script should finish his work asap.
Try this:
select sum(num_tax_amount+num_total_amount) from table_name;
// Get the focused element:
var $focused = $(':focus');
// No jQuery:
var focused = document.activeElement;
// Does the element have focus:
var hasFocus = $('foo').is(':focus');
// No jQuery:
elem === elem.ownerDocument.activeElement;
Which one should you use? quoting the jQuery docs:
As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare
$(':focus')
is equivalent to$('*:focus')
. If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.
The answer is:
document.activeElement
And if you want a jQuery object wrapping the element:
$(document.activeElement)
No, sadly:
The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps
From Co-authoring overview (SharePoint Server 2010)
...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
I fix the problem with under statement ; send data with url same GET methode
$.ajax({
url: 'includes/get_ajax_function.php?value=jack&id='+id,
type: 'post',
data: $('#b-info1').serializeArray(),
and get value with $_REQUEST['value']
OR $_GET['id']
Something that just happened to me and caused me some headaches:
I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).
The script had several of those "code" blocks:
rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.
Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.
... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:
rabbitmqctl change_password test test
(Another solution would have been to delete all users and then call the script again)
this can be resolved by copying the below code in application.properties
spring.thymeleaf.enabled=false
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
Just as an addendum to OP accepted answer:
If you having issues with
fatal: bad object xxxxx
that's because you don't have access to that commit. Which means you don't have that repo stored locally. Then:
git remote add LABEL_FOR_THE_REPO REPO_YOU_WANT_THE_COMMIT_FROM
git fetch LABEL_FOR_THE_REPO
git cherry-pick xxxxxxx
Where xxxxxxx is the commit hash you want.
You need to define the output parameter as an output parameter in the code with the ParameterDirection.Output
enumeration. There are numerous examples of this out there, but here's one on MSDN.
You can't alloc UIImage, this is impossible. Proper code with UIImageView allocate:
UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;
Draw image:
CGContextDrawImage(context, rect, _image.image.CGImage);
You can utilize the dependency management mechanism.
If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.
I'm not sure if that really saves you any code, but it is a cleaner solution IMO.
If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.
ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
I understand that this question is a bit old but I'm going to introduce another solution using redux-observable aka. Epic.
Quoting the official documentation:
What is redux-observable?
RxJS 5-based middleware for Redux. Compose and cancel async actions to create side effects and more.
An Epic is the core primitive of redux-observable.
It is a function which takes a stream of actions and returns a stream of actions. Actions in, actions out.
In more or less words, you can create a function that receives actions through a Stream and then return a new stream of actions (using common side effects such as timeouts, delays, intervals, and requests).
Let me post the code and then explain a bit more about it
store.js
import {createStore, applyMiddleware} from 'redux'
import {createEpicMiddleware} from 'redux-observable'
import {Observable} from 'rxjs'
const NEW_NOTIFICATION = 'NEW_NOTIFICATION'
const QUIT_NOTIFICATION = 'QUIT_NOTIFICATION'
const NOTIFICATION_TIMEOUT = 2000
const initialState = ''
const rootReducer = (state = initialState, action) => {
const {type, message} = action
console.log(type)
switch(type) {
case NEW_NOTIFICATION:
return message
break
case QUIT_NOTIFICATION:
return initialState
break
}
return state
}
const rootEpic = (action$) => {
const incoming = action$.ofType(NEW_NOTIFICATION)
const outgoing = incoming.switchMap((action) => {
return Observable.of(quitNotification())
.delay(NOTIFICATION_TIMEOUT)
//.takeUntil(action$.ofType(NEW_NOTIFICATION))
});
return outgoing;
}
export function newNotification(message) {
return ({type: NEW_NOTIFICATION, message})
}
export function quitNotification(message) {
return ({type: QUIT_NOTIFICATION, message});
}
export const configureStore = () => createStore(
rootReducer,
applyMiddleware(createEpicMiddleware(rootEpic))
)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {configureStore} from './store.js'
import {Provider} from 'react-redux'
const store = configureStore()
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
import {connect} from 'react-redux'
import {newNotification} from './store.js'
class App extends Component {
render() {
return (
<div className="App">
{this.props.notificationExistance ? (<p>{this.props.notificationMessage}</p>) : ''}
<button onClick={this.props.onNotificationRequest}>Click!</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
notificationExistance : state.length > 0,
notificationMessage : state
}
}
const mapDispatchToProps = (dispatch) => {
return {
onNotificationRequest: () => dispatch(newNotification(new Date().toDateString()))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
The key code to solve this problem is as easy as pie as you can see, the only thing that appears different from the other answers is the function rootEpic.
Point 1. As with sagas, you have to combine the epics in order to get a top level function that receives a stream of actions and returns a stream of actions, so you can use it with the middleware factory createEpicMiddleware. In our case we only need one so we only have our rootEpic so we don't have to combine anything but it's a good to know fact.
Point 2. Our rootEpic which takes care about the side effects logic only takes about 5 lines of code which is awesome! Including the fact that is pretty much declarative!
Point 3. Line by line rootEpic explanation (in comments)
const rootEpic = (action$) => {
// sets the incoming constant as a stream
// of actions with type NEW_NOTIFICATION
const incoming = action$.ofType(NEW_NOTIFICATION)
// Merges the "incoming" stream with the stream resulting for each call
// This functionality is similar to flatMap (or Promise.all in some way)
// It creates a new stream with the values of incoming and
// the resulting values of the stream generated by the function passed
// but it stops the merge when incoming gets a new value SO!,
// in result: no quitNotification action is set in the resulting stream
// in case there is a new alert
const outgoing = incoming.switchMap((action) => {
// creates of observable with the value passed
// (a stream with only one node)
return Observable.of(quitNotification())
// it waits before sending the nodes
// from the Observable.of(...) statement
.delay(NOTIFICATION_TIMEOUT)
});
// we return the resulting stream
return outgoing;
}
I hope it helps!
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.
A modification of the code by @CarloCannas:
public static void sudo(String...strings) {
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
(You are welcome to find a better place for outputStream.close())
Usage example:
private static void suMkdirs(String path) {
if (!new File(path).isDirectory()) {
sudo("mkdir -p "+path);
}
}
Update: To get the result (the output to stdout), use:
public static String sudoForResult(String...strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try{
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e){
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
The utility to silently close a number of Closeables (So?ket may be no Closeable) is:
public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
Log.d("closing: "+x);
if (x instanceof Closeable) {
((Closeable)x).close();
} else if (x instanceof Socket) {
((Socket)x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket)x).close();
} else {
Log.d("cannot close: "+x);
throw new RuntimeException("cannot close "+x);
}
} catch (Throwable e) {
Log.x(e);
}
}
}
}
}
try this,
http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html
Encountered the same issue with a ASP.Net Web App and two library class projects which needed to be referenced within the Web App. I had no information provided on why the build failed and the references were invalid.
Solution was to ensure all projects had the same Target Framework:
In Visual Studio 2015- Right Click project > Properties > Application > Target Framework
Save, Clean and Rebuild solution. The project references should no longer appear as yellow warnings and the solution will compile.
My Web App was targeting .Net 4.5 whereas the other two dependent library class projects targeted .Net v4.5.2
There are some good answer above and here is the ES6 Arrow function version
var something = async() => {
let result = await functionThatReturnsPromiseA();
return result + 1;
}
This is an example OPML parser working with FeedDemon opml files:
Sub debugPrintOPML()
' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx
' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx
' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions
' References: Microsoft XML
Dim xmldoc As New DOMDocument60
Dim oNodeList As IXMLDOMSelection
Dim oNodeList2 As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n As Long, n2 As Long, x As Long
Dim strXPathQuery As String
Dim attrLength As Byte
Dim FilePath As String
FilePath = "rss.opml"
xmldoc.Load CurrentProject.Path & "\" & FilePath
strXPathQuery = "opml/body/outline"
Set oNodeList = xmldoc.selectNodes(strXPathQuery)
For n = 0 To (oNodeList.length - 1)
Set curNode = oNodeList.Item(n)
attrLength = curNode.Attributes.length
If attrLength > 1 Then ' or 2 or 3
Call processNode(curNode)
Else
Call processNode(curNode)
strXPathQuery = "opml/body/outline[position() = " & n + 1 & "]/outline"
Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)
For n2 = 0 To (oNodeList2.length - 1)
Set curNode = oNodeList2.Item(n2)
Call processNode(curNode)
Next
End If
Debug.Print "----------------------"
Next
Set xmldoc = Nothing
End Sub
Sub processNode(curNode As IXMLDOMNode)
Dim sAttrName As String
Dim sAttrValue As String
Dim attrLength As Byte
Dim x As Long
attrLength = curNode.Attributes.length
For x = 0 To (attrLength - 1)
sAttrName = curNode.Attributes.Item(x).nodeName
sAttrValue = curNode.Attributes.Item(x).nodeValue
Debug.Print sAttrName & " = " & sAttrValue
Next
Debug.Print "-----------"
End Sub
This one takes multilevel trees of folders (Awasu, NewzCrawler):
...
Call xmldocOpen4
Call debugPrintOPML4(Null)
...
Dim sText4 As String
Sub debugPrintOPML4(strXPathQuery As Variant)
Dim xmldoc4 As New DOMDocument60
'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?
Dim oNodeList As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n4 As Long
If IsNull(strXPathQuery) Then strXPathQuery = "opml/body/outline"
' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx
xmldoc4.async = False
xmldoc4.loadXML sText4
If (xmldoc4.parseError.errorCode <> 0) Then
Dim myErr
Set myErr = xmldoc4.parseError
MsgBox ("You have error " & myErr.reason)
Else
' MsgBox xmldoc4.xml
End If
Set oNodeList = xmldoc4.selectNodes(strXPathQuery)
For n4 = 0 To (oNodeList.length - 1)
Set curNode = oNodeList.Item(n4)
Call processNode4(strXPathQuery, curNode, n4)
Next
Set xmldoc4 = Nothing
End Sub
Sub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)
Dim sAttrName As String
Dim sAttrValue As String
Dim x As Long
For x = 0 To (curNode.Attributes.length - 1)
sAttrName = curNode.Attributes.Item(x).nodeName
sAttrValue = curNode.Attributes.Item(x).nodeValue
'If sAttrName = "text"
Debug.Print strXPathQuery & " :: " & sAttrName & " = " & sAttrValue
'End If
Next
Debug.Print ""
If curNode.childNodes.length > 0 Then
Call debugPrintOPML4(strXPathQuery & "[position() = " & n4 + 1 & "]/" & curNode.nodeName)
End If
End Sub
Sub xmldocOpen4()
Dim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference
Dim oFS
Dim FilePath As String
FilePath = "rss_awasu.opml"
Set oFS = oFSO.OpenTextFile(CurrentProject.Path & "\" & FilePath)
sText4 = oFS.ReadAll
oFS.Close
End Sub
or better:
Sub xmldocOpen4()
Dim FilePath As String
FilePath = "rss.opml"
' function ConvertUTF8File(sUTF8File):
' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA
' loading and conversion from Utf-8 to UTF
sText8 = ConvertUTF8File(CurrentProject.Path & "\" & FilePath)
End Sub
but I don't understand, why xmldoc4 should be loaded each time.
A naive approach could look like this:
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
std::map<std::string, std::string> options; // global?
void parse(std::istream & cfgfile)
{
for (std::string line; std::getline(cfgfile, line); )
{
std::istringstream iss(line);
std::string id, eq, val;
bool error = false;
if (!(iss >> id))
{
error = true;
}
else if (id[0] == '#')
{
continue;
}
else if (!(iss >> eq >> val >> std::ws) || eq != "=" || iss.get() != EOF)
{
error = true;
}
if (error)
{
// do something appropriate: throw, skip, warn, etc.
}
else
{
options[id] = val;
}
}
}
Now you can access each option value from the global options
map anywhere in your program. If you want castability, you could make the mapped type a boost::variant
.
I come to Pandas from an R background, and I see that Pandas is more complicated when it comes to selecting rows or columns.
I had to wrestle with it for a while, and then I found some ways to deal with:
Getting the number of columns:
len(df.columns)
## Here:
# df is your data.frame
# df.columns returns a string. It contains column's titles of the df.
# Then, "len()" gets the length of it.
Getting the number of rows:
len(df.index) # It's similar.
with latest Glide library
use Gradle:
repositories {
mavenCentral()
google()
}
dependencies {
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
}
in activity or fragment:
ImageView imageView = findViewById(R.id.imageView);
/* from internet*/
Glide.with(this)
.load("https://media.giphy.com/media/98uBZTzlXMhkk/giphy.gif")
.into(imageView);
/*from raw folder*/
Glide.with(this)
.load(R.raw.giphy)
.into(imageView);
In case your goal is to have a rotated image in an imageView or file you can use Exif to achieve that. The support library now offers that: https://android-developers.googleblog.com/2016/12/introducing-the-exifinterface-support-library.html
Below is its usage but to achieve your goal you have to check the library api documentation for that. I just wanted to give a hint that rotating the bitmap isn't always the best way.
Uri uri; // the URI you've received from the other app
InputStream in;
try {
in = getContentResolver().openInputStream(uri);
ExifInterface exifInterface = new ExifInterface(in);
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
// Handle any errors
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
int rotation = 0;
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotation = 270;
break;
}
dependency
compile "com.android.support:exifinterface:25.1.0"
Try using absolute positioning, rather than relative positioning
this should get you close - you can adjust by tweaking margins or top/left positions
#play_button {
position:absolute;
transition: .5s ease;
top: 50%;
left: 50%;
}
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
FirebaseAuth firebaseauth = FirebaseAuth.getInstance();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); //displays text of header of nav drawer.
View headerview = navigationView.getHeaderView(0);
TextView tt1 = (TextView) headerview.findViewById(R.id.textview_username);
tt1.setText(firebaseauth.getCurrentUser().getDisplayName());//username of logged in user.
TextView tt = (TextView) headerview.findViewById(R.id.textView_emailid);
tt.setText(firebaseauth.getCurrentUser().getEmail()); //email id of logged in user.
final ImageView img1 = (ImageView) headerview.findViewById(R.id.imageView_userimage);
Glide.with(getApplicationContext())
.load(firebaseauth.getCurrentUser().getPhotoUrl()).asBitmap().atMost().error(R.drawable.ic_selfie_point_icon) //asbitmap after load always.
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
img1.setImageBitmap(resource);
}
});
I have made this code by myself with some logic...Its 100% working.....pls do upvote my ans.
The textview and imageview are from @layout/nav_header_main.xml
many interesting answers here, all about the same, except... which one's faster?
import numpy
np_clip = numpy.clip
mm_clip = lambda x, l, u: max(l, min(u, x))
s_clip = lambda x, l, u: sorted((x, l, u))[1]
py_clip = lambda x, l, u: l if x < l else u if x > u else x
>>> import random
>>> rrange = random.randrange
>>> %timeit mm_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 1.02 µs per loop
>>> %timeit s_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 1.21 µs per loop
>>> %timeit np_clip(rrange(100), 10, 90)
100000 loops, best of 3: 6.12 µs per loop
>>> %timeit py_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 783 ns per loop
paxdiablo has it!, use plain ol' python. The numpy version is, perhaps not surprisingly, the slowest of the lot. Probably because it's looking for arrays, where the other versions just order their arguments.
To anyone else who ended up here while searching for info on how to decode a string encoded with Base64.encodeBytes()
, here was my solution:
// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());
// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2);
String val2 = new String(tmp2, "UTF-8");
Also, I'm supporting older versions of Android so I'm using Robert Harder's Base64 library from http://iharder.net/base64
Why not just do
if(BuildConfig.DEBUG)
Log.d("tag","msg");
? No additional libraries needed, no proguard rules which tend to screw up the project and java compiler will just leave out bytecode for for this call when you make release build.
dict = {}
for i in set(str):
b = str.count(i, 0, len(str))
dict[i] = b
print dict
If my string is:
str = "this is string!"
Above code will print:
{'!': 1, ' ': 2, 'g': 1, 'i': 3, 'h': 1, 'n': 1, 's': 3, 'r': 1, 't': 2}
In .NET 4 you don't need the ToArray()
call - string.Join
is overloaded to accept IEnumerable<T>
or just IEnumerable<string>
.
There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?
You could iterate over the list, work out the final size, allocate a StringBuilder
of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
Using pipeline:
echo your_pswd | sudo -S your_cmd
Using here-document:
sudo -S cmd <<eof
pwd
eof
#remember to put the above two lines without "any" indentations.
Open a terminal to ask password (whichever works):
gnome-terminal -e "sudo cmd"
xterm -e "sudo cmd"
Missing ;
after var_dump($row)
To find the Flutter SDK path [ used Windows10 ]
You will see the path at the top
In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.
Solution for loading an external website into an iFrame even tough the x-frame option is set to deny on the external website.
If you want to load a other website into an iFrame and you get the Display forbidden by X-Frame-Options”
error then you can actually overcome this by creating a server side proxy script.
The src
attribute of the iFrame could have an url looking like this: /proxy.php?url=https://www.example.com/page&key=somekey
Then proxy.php would look something like:
if (isValidRequest()) {
echo file_get_contents($_GET['url']);
}
function isValidRequest() {
return $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['key']) &&
$_GET['key'] === 'somekey';
}
This by passes the block, because it is just a GET request that might as wel have been a ordinary browser page visit.
Be aware: You might want to improve the security in this script. Because hackers could start loading in webpages via your proxy script.
This problem arises due to incompatible JDK version. Download and install latest JDK(currently its 8) from java official site in case you are using previous versions. Then in Android Studio go to File->Project Structure->SDK location -> JDK location and set it to 'C:\Program Files\Java\jdk1.8.0_121' (Default location of JDK). Gradle sync your project and you are all set...
If you are using iframe for vimeo, change the url from:
to:
It works for me.
My guess is Nuget Package Manager is messing up with VSO. I create a new project, add packages to it just fine, check in TFS. Then I go home, "Get Latest Version", and Run, and fail because Nuget Package Manager doesn't restore my packages. Solution: on my home machine
You can also "fix" this by replacing the image with its inline Base64 representation:
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only. img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
if you user $criteria, I recommend blow usage:
$criteria = new CDbCriteria();
$criteria->compare('email_id', 101);
$comments = EmailArchive::model()->findAll($criteria);
Might found a solution very easy which you only need to create different type of
. Seem to have worked for me.
example : (html code)
<br/ class="150%space">
(css code)
br[class='150%space']
{
line-height: 150%;
}
For those who are looking for a tiny and smart solution:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
To use center alignment in ionic app code itself, you can use the following code:
<ion-row center>
<ion-col text-center>
<button ion-button>Search</button>
</ion-col>
</ion-row>
To use right alignment in ionic app code itself, you can use the following code:
<ion-row right>
<ion-col text-right>
<button ion-button>Search</button>
</ion-col>
</ion-row>
Object Model is concerned with the following three concepts Data Abstraction Encapsulation Inheritance The relational model used the basic concept of a relation or table. Object-relational mapping (OR mapping) products integrate object programming language capabilities with relational databases.
The proper answer to your question is to use statistics.mean
. But for fun, here is a version of mean that does not use the len()
function, so it (like statistics.mean
) can be used on generators, which do not support len()
:
from functools import reduce
from operator import truediv
def ave(seq):
return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]),
enumerate(seq, start=1),
(0, 0)))
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
yourTextField.tintColor = [UIColor whiteColor];
It works if you set it in code, 'cos somehow color trigger doesn't do it in the Interface Builder (Xcode 6.1.1). It suited well without a need to change any appearance proxy.
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
shell@android:/ $ dumpsys cpuinfo
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
47% 1118/com.wxg.sodproject: 12% user + 35% kernel
1.6% 1225/android.process.media: 1% user + 0.6% kernel
1.3% 263/mpdecision: 0.1% user + 1.2% kernel
0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
0.1% 883/com.android.systemui: 0.1% user + 0% kernel
0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
0% 118/mmcqd/0: 0% user + 0% kernel
0% 179/surfaceflinger: 0% user + 0% kernel
0% 46/kinteractiveup: 0% user + 0% kernel
0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
0% 239/sdcard: 0% user + 0% kernel
0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait
The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length
of the collection returned by the selector or check whether the first array element is 'undefined'.
You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.
$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1
How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__
, __lt__
, etc all return boolean arrays where the given condition is true).
E.g.
x = np.arange(9).reshape(3,3)
print x > 5
yields:
array([[False, False, False],
[False, False, False],
[ True, True, True]], dtype=bool)
This is the same reason why something like if x > 5:
raises a ValueError if x
is a numpy array. It's an array of True/False values, not a single value.
Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5]
yields [6 7 8]
, in this case.
Honestly, it's fairly rare that you actually need numpy.where
but it just returns the indicies where a boolean array is True
. Usually you can do what you need with simple boolean indexing.
Assume I have below array:
Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];
If we want to get item with Id = 1
and Name = "oily skin"
, We'll try as below:
var skinName = skins.find(x=>x.Id == "1").Name;
The result will return the skinName is "Oily skin".
I had a problem similar to the one posed in the original question. I was intrigued by the divs styled as table elements (didn't know you could do that!) and gave it a run. However, my solution was to keep my tables wrapped in tags, but rename each input and select option to become the keys of array, which I'm now parsing to get each element in the selected row.
Here's a single row from the table. Note that key [4] is the rendered ID of the row in the database from which this table row was retrieved:
<table>
<tr>
<td>DisabilityCategory</td>
<td><input type="text" name="FormElem[4][ElemLabel]" value="Disabilities"></td>
<td><select name="FormElem[4][Category]">
<option value="1">General</option>
<option value="3">Disability</option>
<option value="4">Injury</option>
<option value="2"selected>School</option>
<option value="5">Veteran</option>
<option value="10">Medical</option>
<option value="9">Supports</option>
<option value="7">Residential</option>
<option value="8">Guardian</option>
<option value="6">Criminal</option>
<option value="11">Contacts</option>
</select></td>
<td>4</td>
<td style="text-align:center;"><input type="text" name="FormElem[4][ElemSeq]" value="0" style="width:2.5em; text-align:center;"></td>
<td>'ccpPartic'</td>
<td><input type="text" name="FormElem[4][ElemType]" value="checkbox"></td>
<td><input type="checkbox" name="FormElem[4][ElemRequired]"></td>
<td><input type="text" name="FormElem[4][ElemLabelPrefix]" value=""></td>
<td><input type="text" name="FormElem[4][ElemLabelPostfix]" value=""></td>
<td><input type="text" name="FormElem[4][ElemLabelPosition]" value="before"></td>
<td><input type="submit" name="submit[4]" value="Commit Changes"></td>
</tr>
</table>
Then, in PHP, I'm using the following method to store in an array ($SelectedElem) each of the elements in the row corresponding to the submit button. I'm using print_r()
just to illustrate:
$SelectedElem = implode(",", array_keys($_POST['submit']));
print_r ($_POST['FormElem'][$SelectedElem]);
Perhaps this sounds convoluted, but it turned out to be quite simple, and it preserved the organizational structure of the table.
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
You can define a context
for your application say ExampleContext
which will hold the context of your application and then use it to instantiate an activity like this:
var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);
Please bear in mind that this code is written in C#
as I use MonoDroid, but I believe it is very similar to Java
. For how to create an ApplicationContext
look at this thread
This is how I made my Application Class
[Application]
public class Application : Android.App.Application, IApplication
{
public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
}
public object MyObject { get; set; }
}
Yes, you can access it through GET
and POST
(trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
First of all go to the device manager now go to View>>select Show hidden devices....Then go to network adapters and find out Microsoft Hosted network Virual Adapter ....Press right click and enable the option....
Then go to command prompt with administrative privileges and enter the following commands:
netsh wlan set hostednetwork mode=allow
netsh wlan start hostednetwork
Your Hostednetwork will work without any problems.
I met this issue due to operation system, simple to different platform about JRE implementation.
new SecureRandom(key.getBytes())
will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.
It means that $objPage
is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes
for the first parameter.
I would like to add that you can extend the compatibility of :scope by just assigning a temporary attribute to the current node.
let node = [...];
let result;
node.setAttribute("foo", "");
result = window.document.querySelectorAll("[foo] > .bar");
// And, of course, you can also use other combinators.
result = window.document.querySelectorAll("[foo] + .bar");
result = window.document.querySelectorAll("[foo] ~ .bar");
node.removeAttribute("foo");
If you are migrating to java7 or using java7 then generally this error can be seen. I faced above errors and struggled a lot to find out the root cause, I would suggest to try adding "-XX:-UseSplitVerifier" JVM argument while running your application.
You can disable them altogether by
(setq make-backup-files nil)
To be honest I don't know that you can. If you just set up a test instance and open Excel twice, because that is what you are talking about happening, if you name one workbook "test1" and another "test2" if you try to move a workbook, or even a worksheet between the two applications they are totally unaware of each other. I also notice odd behavior while simply manually cutting and pasting from Excel instance 1 and Excel instance 2.
You may have to write two macros kind of a drop off and then a pick up from a location that you share between them. Maybe a command button on the tool bar.
Maybe one of the super excel guys on here have a better answer.
As the other answers state:
count
will perform an SQL COUNT
querylength
will calculate the length of the resulting arraysize
will try to pick the most appropriate of the two to avoid excessive queriesBut there is one more thing. We noticed a case where size
acts differently to count
/length
altogether, and I thought I'd share it since it is rare enough to be overlooked.
If you use a :counter_cache
on a has_many
association, size
will use the cached count directly, and not make an extra query at all.
class Image < ActiveRecord::Base
belongs_to :product, counter_cache: true
end
class Product < ActiveRecord::Base
has_many :images
end
> product = Product.first # query, load product into memory
> product.images.size # no query, reads the :images_count column
> product.images.count # query, SQL COUNT
> product.images.length # query, loads images into memory
This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.
I recently ran into a problem with a UICommand not invoking in a JSF 1.2 application using IBM Extended Faces Components.
I had a command button on a row of a datatable (the extended version, so <hx:datatable>
) and the UICommand would not fire from certain rows from the table (the rows that would not fire were the rows greater than the default row display size).
I had a drop-down component for selecting number of rows to display. The value backing this field was in RequestScope
. The data backing the table itself was in a sort of ViewScope
(in reality, temporarily in SessionScope
).
If the row display was increased via the control which value was also bound to the datatable's rows
attribute, none of the rows displayed as a result of this change could fire the UICommand when clicked.
Placing this attribute in the same scope as the table data itself fixed the problem.
I think this is alluded to in BalusC #4 above, but not only did the table value need to be View or Session scoped but also the attribute controlling the number of rows to display on that table.
Adding;
display: inline-block;
to the child elements will prevent them being split between columns.
curl performs SSL
certificate verification by default, using a "bundle"
of Certificate Authority (CA)
public keys (CA certs). The default
bundle is named curl-ca-bundle.crt; you can specify an alternate file
using the --cacert option.
If this HTTPS
server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure
) option.
for example
curl --insecure http://........
You could use the LINQ select
clause and reference the property that relates to your Name column.
I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()
My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:
{{'0' if linked_contacts == None else linked_contacts|length}}
For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")
lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)
def clearFrame():
# destroy all widgets from frame
for widget in frame.winfo_children():
widget.destroy()
# this will clear frame and frame will be empty
# if you want to hide the empty panel then
frame.pack_forget()
frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)
# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()
Another solutions is - Backing Up and Restoring Database
Back Up the System Database
To back up the system database using Microsoft SQL Server Management Studio Express, follow the steps below:
Download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593
After Microsoft SQL Server Management Studio Express has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server name:" field, enter the name of the Webtrends server on which the system database is installed. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.
Select "OK" to complete the backup process.
Repeat the above steps for the "wtMaster" part of the database.
Restore the System Database
To restore the system database using Microsoft SQL Server Management Studio, follow the steps below:
If you haven't already, download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593
After Microsoft SQL Server Management Studio has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server type:" field, select "Database Engine" (default). In the "Server name:" field, select "\WTSYSTEMDB" where is the name of the Webtrends server where the database is located. WTSYSTEMDB is the name of the database instance in a default installation. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.
Expand "Databases", right-click on "wt_sched" and select "Delete" from the context menu. Make sure "Delete backup and restore history information for databases" check-box is checked.
Select "OK" to complete the deletion process.
Repeat the above steps for the "wtMaster" part of the database.
Right click on "Databases" and select "Restore Database..." from the context menu. In the "To database:" field type in "wt_sched". Select the "From device:" radio button. Click on the ellipse (...) to the right of the "From device:" text field. Click the "Add" button. Navigate to and select the backup file for "wt_sched". Select "OK" on the "Locate Backup File" form. Select "OK" on the "Specify Backup" form. Check the check-box in the restore column next to "wt_sched-Full Database Backup". Select "OK" on the "Restore Database" form.
Repeat step 6 for the "wtMaster" part of the database.
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Steps:
Example
x=pd.DataFrame([1,2,3,4])
def add(i1, i2):
return i1+i2
x.apply(add,i2=9)
The outcome of this example is that each number in the dataframe will be added to the number 9.
0
0 10
1 11
2 12
3 13
Explanation:
The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".
There are different approaches to refresh the current route
Change router behaviour (Since Angular 5.1) Set the routers onSameUrlNavigation to 'reload'. This will emit the router events on same URL Navigation.
Leave the router untouched
I have written a more detailed explanation under https://medium.com/@kevinkreuzer/refresh-current-route-in-angular-512a19d58f6e
Hope this helps.
This also works:
REPLACE(ISNULL(CONVERT(DATE, @date), ''), '1900-01-01', '') AS 'Your Date Field'
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
The answer was already given, but I just want to give my piece of cake. What you want to achieve is called method borrowing
in the context of JS, that when we take a method from an object and call it in the context of another object. It is quite common to take array methods and apply them to arguments. Let me give you an example.
So we have "super" hashing function which takes two numbers as an argument and returns "super safe" hashed string:
function hash() {
return arguments[0]+','+arguments[1];
}
hash(1,2); // "1,2" whoaa
So far so good, but we have little problem with the above approach, it is constrained, only works with two numbers, that is not dynamic, let's make it work with any number and plus you do not have to pass an array (you can if you still insist). Ok, Enough talk, Let's fight!
The natural solution would be to use arr.join
method:
function hash() {
return arguments.join();
}
hash(1,2,4,..); // Error: arguments.join is not a function
Oh, man. Unfortunately, that won’t work. Because we are calling hash(arguments) and arguments object is both iterable and array-like, but not a real array. How about the below approach?
function hash() {
return [].join.call(arguments);
}
hash(1,2,3,4); // "1,2,3,4" whoaa
The trick is called method borrowing.
We borrow a join
method from a regular array [].join.
And use [].join.call
to run it in the context of arguments
.
Why does it work?
That’s because the internal algorithm of the native method arr.join(glue)
is very simple.
Taken from the specification almost “as-is”:
Let glue be the first argument or, if no arguments, then a comma ",".
Let result be an empty string.
Append this[0] to result.
Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.
Return result.
So, technically it takes this and joins this[0], this[1] …etc together. It’s intentionally written in a way that allows any array-like this (not a coincidence, many methods follow this practice). That’s why it also works with this=arguments.
I like this one. Simple, and you can have more than one parameter for each argument:
final Map<String, List<String>> params = new HashMap<>();
List<String> options = null;
for (int i = 0; i < args.length; i++) {
final String a = args[i];
if (a.charAt(0) == '-') {
if (a.length() < 2) {
System.err.println("Error at argument " + a);
return;
}
options = new ArrayList<>();
params.put(a.substring(1), options);
}
else if (options != null) {
options.add(a);
}
else {
System.err.println("Illegal parameter usage");
return;
}
}
For example:
-arg1 1 2 --arg2 3 4
System.out.print(params.get("arg1").get(0)); // 1
System.out.print(params.get("arg1").get(1)); // 2
System.out.print(params.get("-arg2").get(0)); // 3
System.out.print(params.get("-arg2").get(1)); // 4
Use [NSIndexPath indexPathForRow:inSection:]
to quickly create an index path.
Edit: In Swift 3:
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
Swift 5
IndexPath(row: 0, section: 0)
I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.
The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.
<style>
body{
max-width: 1180px;
width: 98%;
margin: 0px auto;
text-align: left;
}
</style>
Just apply this style before applying any CSS. You can change width as per your need.
import java.io.UnsupportedEncodingException;
/**
* File: BOM.java
*
* check if the bom character is present in the given string print the string
* after skipping the utf-8 bom characters print the string as utf-8 string on a
* utf-8 console
*/
public class BOM
{
private final static String BOM_STRING = "Hello World";
private final static String ISO_ENCODING = "ISO-8859-1";
private final static String UTF8_ENCODING = "UTF-8";
private final static int UTF8_BOM_LENGTH = 3;
public static void main(String[] args) throws UnsupportedEncodingException {
final byte[] bytes = BOM_STRING.getBytes(ISO_ENCODING);
if (isUTF8(bytes)) {
printSkippedBomString(bytes);
printUTF8String(bytes);
}
}
private static void printSkippedBomString(final byte[] bytes) throws UnsupportedEncodingException {
int length = bytes.length - UTF8_BOM_LENGTH;
byte[] barray = new byte[length];
System.arraycopy(bytes, UTF8_BOM_LENGTH, barray, 0, barray.length);
System.out.println(new String(barray, ISO_ENCODING));
}
private static void printUTF8String(final byte[] bytes) throws UnsupportedEncodingException {
System.out.println(new String(bytes, UTF8_ENCODING));
}
private static boolean isUTF8(byte[] bytes) {
if ((bytes[0] & 0xFF) == 0xEF &&
(bytes[1] & 0xFF) == 0xBB &&
(bytes[2] & 0xFF) == 0xBF) {
return true;
}
return false;
}
}
for react-router V5 and above use below syntax for multiple paths
<Route
exact
path={[path1, path2]}
component={component}
/>
For me it was an issue with deviceToken
. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
});
If it happens when you try to install some package via composer just use this command COMPOSER_MEMORY_LIMIT=-1 composer require nameofpackage
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
The following tested working
<iframe style="width:100%; height:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" src="index.html" frameborder="0" height="100%" width="100%"></iframe>
You are all wrong! Why? Because all you need is this code to work:
(image View) / C# Img is : your Image box
Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :
private void Button_Click(object sender, RoutedEventArgs e)
{
img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
}
The second thing i did was Uninstall my Anti-Virus software (AVG Antivirus) {sounds crazy but, i had to}. it reduced gradle build time upto 40%
The first thing i did was enable offline mode (1. click on Gradle usually on the right side of the editor 2. click on the connection button to toggle) it reduced the gradle build time for upto 20%
so my Gradle build time was reduced for upto 60% by doing these two things
This design was not mentioned yet:
Though it has limitations, if you can bear them, it's very simple and very efficient. Features:
Here follows an example - taxonomic tree of birds so the hierarchy is Class/Order/Family/Genus/Species - species is the lowest level, 1 row = 1 taxon (which corresponds to species in the case of the leaf nodes):
CREATE TABLE `taxons` (
`TaxonId` smallint(6) NOT NULL default '0',
`ClassId` smallint(6) default NULL,
`OrderId` smallint(6) default NULL,
`FamilyId` smallint(6) default NULL,
`GenusId` smallint(6) default NULL,
`Name` varchar(150) NOT NULL default ''
);
and the example of the data:
+---------+---------+---------+----------+---------+-------------------------------+
| TaxonId | ClassId | OrderId | FamilyId | GenusId | Name |
+---------+---------+---------+----------+---------+-------------------------------+
| 254 | 0 | 0 | 0 | 0 | Aves |
| 255 | 254 | 0 | 0 | 0 | Gaviiformes |
| 256 | 254 | 255 | 0 | 0 | Gaviidae |
| 257 | 254 | 255 | 256 | 0 | Gavia |
| 258 | 254 | 255 | 256 | 257 | Gavia stellata |
| 259 | 254 | 255 | 256 | 257 | Gavia arctica |
| 260 | 254 | 255 | 256 | 257 | Gavia immer |
| 261 | 254 | 255 | 256 | 257 | Gavia adamsii |
| 262 | 254 | 0 | 0 | 0 | Podicipediformes |
| 263 | 254 | 262 | 0 | 0 | Podicipedidae |
| 264 | 254 | 262 | 263 | 0 | Tachybaptus |
This is great because this way you accomplish all the needed operations in a very easy way, as long as the internal categories don't change their level in the tree.
import { HttpModule } from '@angular/http';
package in your module.ts file and add it in your imports.
You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:
I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).
public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)
See similar C# string.ToLower() and string.ToLowerInvariant()
Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html
FWIW, here is my approach = a simple one that works for me:
<div id="outerDivWrapper">
<div id="outerDiv">
<div id="scrollableContent">
blah blah blah
</div>
</div>
</div>
html, body {
height: 100%;
margin: 0em;
}
#outerDivWrapper, #outerDiv {
height: 100%;
margin: 0em;
}
#scrollableContent {
height: 100%;
margin: 0em;
overflow-y: auto;
}
If only the column names are available like :
cnms <- c("Nam1","Nam2","Nam3")
To create an empty data frame with the above variable names, first create a data.frame
object:
emptydf <- data.frame()
Now call zeroth element of every column, thus creating an empty data frame with the given variable names:
for( i in 1:length(cnms)){
emptydf[0,eval(cnms[i])]
}
Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).
Virtual functions are declared and defined in normal class.
Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.
An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.
The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.
Horizontal center:
left: 50%;
transform: translateX(-50%);
Vertical center:
top: 50%;
transform: translateY(-50%);
Both horizontal and vertical:
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Compatibility is not an issue: http://caniuse.com/#feat=transforms2d
It's possible to use TUN/TAP device. http://tuntaposx.sourceforge.net/
Try The Below Code It Works In Normal State
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/TextLabel">
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hiiiii"
android:id="@+id/edit_id"/>
</android.support.design.widget.TextInputLayout>
In Styles Folder TextLabel Code
<style name="TextLabel" parent="TextAppearance.AppCompat">
<!-- Hint color and label color in FALSE state -->
<item name="android:textColorHint">@color/Color Name</item>
<item name="android:textSize">20sp</item>
<!-- Label color in TRUE state and bar color FALSE and TRUE State -->
<item name="colorAccent">@color/Color Name</item>
<item name="colorControlNormal">@color/Color Name</item>
<item name="colorControlActivated">@color/Color Name</item>
</style>
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
It also happens when apple developer account expires for stopped payment. The old cert may be still usable to debug breakpoint for a week or few. Then one day all the sudden debug stepping on iPhone devices will be denied.
The solution is re-generate cert after paying for developer account. It may take some hours to get activated by apple.
Remember to delete old certs(ios dev, apple worldwide,) in keychain app of your mac. Revoke old cert in apple developer website optionally for cleanup. And create new one (with xcode directly is also fine) That will enable iphone debug.
Working with just one class:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep() --- just a function that waits a certain amount of milliseconds
using namespace std;
int main()
{
clock_t cl; //initializing a clock type
cl = clock(); //starting time of clock
_sleep(5167); //insert code here
cl = clock() - cl; //end point of clock
_sleep(1000); //testing to see if it actually stops at the end point
cout << cl/(double)CLOCKS_PER_SEC << endl; //prints the determined ticks per second (seconds passed)
return 0;
}
//outputs "5.17"
After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.
You can ask the DB which queries are running as that just a table query. Look at the V$ tables.
Quick Example:
SELECT sid,
opname,
sofar,
totalwork,
units,
elapsed_seconds,
time_remaining
FROM v$session_longops
WHERE sofar != totalwork;
$("#dialog").dialog({
autoOpen: false,
resizable: false,
width: 400,
height: 140,
modal: true,
buttons: {
"SUBMIT": function() {
$("form").submit();
},
"CANCEL": function() {
$(this).dialog("close");
}
},
close: function() {
alert('close');
}
});
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.
Add a class as Public and use it very easily like convertToInt32()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Common
/// </summary>
public static class Common
{
public static double ConvertToDouble(string Value) {
if (Value == null) {
return 0;
}
else {
double OutVal;
double.TryParse(Value, out OutVal);
if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
return 0;
}
return OutVal;
}
}
}
Then Call The Function
double DirectExpense = Common.ConvertToDouble(dr["DrAmount"].ToString());
I think you can remove all your log with switch from full to simple recovery. Right click on your Database and select Properties
and select Options
and change
Recovery mode
to Simple
Containment type
to None
The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:
...
startTimer = () => {
let interval = setInterval(this.timer.bind(this), 1000);
this.setState({ interval });
};
As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).
Another option is to use another arrow function:
startTimer = () => {
let interval = setInterval(() => this.timer(), 1000);
this.setState({ interval });
};
To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.
I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:
String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.
In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.
<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">
All of those will render tooltips in most every browser.
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Here I am giving you a proper example of one callback method . so suppose we have a method like method login() :
public void login() {
loginService = new LoginService();
loginService.login(loginProvider, new LoginListener() {
@Override
public void onLoginSuccess() {
loginService.getresult(true);
}
@Override
public void onLoginFaliure() {
loginService.getresult(false);
}
});
System.out.print("@@##### get called");
}
I also put all the helper class here to make the example more clear: loginService class
public class LoginService implements Login.getresult{
public void login(LoginProvider loginProvider,LoginListener callback){
String username = loginProvider.getUsername();
String pwd = loginProvider.getPassword();
if(username != null && pwd != null){
callback.onLoginSuccess();
}else{
callback.onLoginFaliure();
}
}
@Override
public void getresult(boolean value) {
System.out.print("login success"+value);
}}
and we have listener LoginListener as :
interface LoginListener {
void onLoginSuccess();
void onLoginFaliure();
}
now I just wanted to test the method login() of class Login
@Test
public void loginTest() throws Exception {
LoginService service = mock(LoginService.class);
LoginProvider provider = mock(LoginProvider.class);
whenNew(LoginProvider.class).withNoArguments().thenReturn(provider);
whenNew(LoginService.class).withNoArguments().thenReturn(service);
when(provider.getPassword()).thenReturn("pwd");
when(provider.getUsername()).thenReturn("username");
login.getLoginDetail("username","password");
verify(provider).setPassword("password");
verify(provider).setUsername("username");
verify(service).login(eq(provider),captor.capture());
LoginListener listener = captor.getValue();
listener.onLoginSuccess();
verify(service).getresult(true);
also dont forget to add annotation above the test class as
@RunWith(PowerMockRunner.class)
@PrepareForTest(Login.class)
I have a similar question here: Writting in sub-ndarray of a ndarray in the most pythonian way. Python 2 .
Following the solution of previous post for your case the solution looks like:
columns_to_keep = [1,3]
rows_to_keep = [1,3]
An using ix_:
x[np.ix_(rows_to_keep, columns_to_keep)]
Which is:
array([[ 5, 7],
[13, 15]])
If you want to do it the dirty way, try this.
@SuppressWarnings("unchecked")
public ArrayList<String> convert(ArrayList<Object> a) {
return (ArrayList) a;
}
Advantage: here you save time by not iterating over all objects.
Disadvantage: may produce a hole in your foot.
You could use an immutable struct
public struct Data
{
public Data(int intValue, string strValue)
{
IntegerData = intValue;
StringData = strValue;
}
public int IntegerData { get; private set; }
public string StringData { get; private set; }
}
var list = new List<Data>();
Or a KeyValuePair<int, string>
using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));
Running the command below worked with. Tried changing server.xml
and the conf file but both didn't work.
/sbin/iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT
/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
Nothing wrong with your method, it's a G-mail security issue.
Login g-mail account settings.
Enable 2-step verification.
Use new-generated password in place of your real g-mail password.
Don't forget to clear cache.
php artisan config:cache.
php artisan config:clear.
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=generatedAppPassword
MAIL_ENCRYPTION=tls
Use Timer and tick event to copy your files.
On start the service, start the time and specify the interval in the time.
So the service is keep running and copy the files ontick.
Hope it help.
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.
In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.
Try recompiling your code with Java 1.7 or upgrade your Java Plugin.
No need to trying reinvent the wheel, as this is common greatest-n-per-group problem. Very nice solution is presented.
I prefer the most simplistic solution (see SQLFiddle, updated Justin's) without subqueries (thus easy to use in views):
SELECT t1.*
FROM lms_attendance AS t1
LEFT OUTER JOIN lms_attendance AS t2
ON t1.user = t2.user
AND (t1.time < t2.time
OR (t1.time = t2.time AND t1.Id < t2.Id))
WHERE t2.user IS NULL
This also works in a case where there are two different records with the same greatest value within the same group - thanks to the trick with (t1.time = t2.time AND t1.Id < t2.Id)
. All I am doing here is to assure that in case when two records of the same user have same time only one is chosen. Doesn't actually matter if the criteria is Id
or something else - basically any criteria that is guaranteed to be unique would make the job here.
As a variation of Bridge's answer (I don't yet have enough rep to comment, and didn't feel right about editing that answer), here is a version that works better for me.
SELECT column_name AS [Name],
IS_NULLABLE AS [Null?],
DATA_TYPE + CASE
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN ''
WHEN CHARACTER_MAXIMUM_LENGTH > 99999 THEN ''
ELSE '(' + Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) + ')'
END AS [Type]
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = 'table_name'
Notable changes:
FlexPaper is probably still the best viewer out there to be used for this kind of stuff. It has a traditional viewer and a more turn page / flip book style viewer both in flash and html5
The property event.which
is added when using jQuery to avoid browser differences. See docs.
The which
property will be undefined if you are not using jQuery.
We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.
import pandas as pd
import seaborn as sns
import numpy as np
numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.
for i in data[numeric_features].columns:
plt.figure(figsize=(12,5))
plt.title(i)
sns.boxplot(data=data[i])
Just remove old APK android/app/build/outputs/apk/debug/app-debug.apk in the folder. that's all. enjoy your coding...
Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).
from sklearn import model_selection
test_size = 0.33
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(feature_vectors, y, test_size=test_size, random_state=seed)
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix
model = LogisticRegression()
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))
y_pred = model.predict(X_test)
print("F1 Score: ", f1_score(y_test, y_pred, average="macro"))
print("Precision Score: ", precision_score(y_test, y_pred, average="macro"))
print("Recall Score: ", recall_score(y_test, y_pred, average="macro"))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
"""
Generate matrix plot of confusion matrix with pretty annotations.
The plot image is saved to disk.
args:
y_true: true label of the data, with shape (nsamples,)
y_pred: prediction of the data, with shape (nsamples,)
filename: filename of figure file to save
labels: string array, name the order of class labels in the confusion matrix.
use `clf.classes_` if using scikit-learn models.
with shape (nclass,).
ymap: dict: any -> string, length == nclass.
if not None, map the labels & ys to more understandable strings.
Caution: original y_true, y_pred and labels must align.
figsize: the size of the figure plotted.
"""
if ymap is not None:
y_pred = [ymap[yi] for yi in y_pred]
y_true = [ymap[yi] for yi in y_true]
labels = [ymap[yi] for yi in labels]
cm = confusion_matrix(y_true, y_pred, labels=labels)
cm_sum = np.sum(cm, axis=1, keepdims=True)
cm_perc = cm / cm_sum.astype(float) * 100
annot = np.empty_like(cm).astype(str)
nrows, ncols = cm.shape
for i in range(nrows):
for j in range(ncols):
c = cm[i, j]
p = cm_perc[i, j]
if i == j:
s = cm_sum[i]
annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
elif c == 0:
annot[i, j] = ''
else:
annot[i, j] = '%.1f%%\n%d' % (p, c)
cm = pd.DataFrame(cm, index=labels, columns=labels)
cm.index.name = 'Actual'
cm.columns.name = 'Predicted'
fig, ax = plt.subplots(figsize=figsize)
sns.heatmap(cm, annot=annot, fmt='', ax=ax)
#plt.savefig(filename)
plt.show()
cm_analysis(y_test, y_pred, model.classes_, ymap=None, figsize=(10,10))
using https://gist.github.com/hitvoice/36cf44689065ca9b927431546381a3f7
Note that if you use rocket_r
it will reverse the colors and somehow it looks more natural and better such as below:
Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is binary(n)
or varbinary(n)
). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.
Not in Linux at the moment, so can't double check, but I think it's:
rpm -ql ffmpeg
That should list all the files installed as part of the ffmpeg package.
We can also create the object in this way:-
String s ="Hello";
Nobody has discuss it.
this function takes the number and precision and returns the rounded off number
float roundoff(float num,int precision)
{
int temp=(int )(num*pow(10,precision));
int num1=num*pow(10,precision+1);
temp*=10;
temp+=5;
if(num1>=temp)
num1+=10;
num1/=10;
num1*=10;
num=num1/pow(10,precision+1);
return num;
}
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.
For me the /**<NEWLINE>
or Shift-Alt-J (or ?-?-J on a Mac) approach works best.
I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.
IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.
The error:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 5 more
is occurring because the current SDK version is incompatible with Java 9.
So, to solve it, you can downgrade your java version to Java 8, or with a workaround, you can export the following option on your terminal:
Linux:
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
Windows:
set JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
And to make it stick, you can export the JAVA_OPTS in your profile file on Linux (.zshrc
, .bashrc
and etc.) or add as an environment permanently on Windows.
Then, you can type the flutter or sdkmanager command:
Flutter:
flutter doctor --android-licenses
sdkmanager:
sdkmanager --licenses
and type Y when needed to accept the licenses.
ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.
Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:
this.TopMost = true;
this.TopMost = false;
I have this code in my form's constructor, eg:
public MyForm()
{
//...
// Brint-to-front hack
this.TopMost = true;
this.TopMost = false;
//...
}
Java, unlike languages like C and C++, treats boolean
as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean
.
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
For anyone still reading this: setTargetFragment()
has been deprecated. It is now recommended to use the FragmentResultListener
API like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("resultKey")
// Do something with the result...
}
...
// Somewhere show your dialog
MyDialogFragment.newInstance().show(parentFragmentManager, "tag")
}
Then in your MyDialogFragment
set the result:
button.setOnClickListener{
val result = "some string"
setFragmentResult("requestKey", bundleOf("resultKey" to result))
dismiss()
}
If you are using Eclipse, for an existing project (which has a build.gradle
file) you can simply type gradle eclipse
which will create all the Eclipse files and folders for this project.
It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.
Yes it can be done. You need to use
position:absolute;
left:0;
right:0;
I think the most intuitive way to do this is by giving the children a "wait" prop
, which hides the component for the duration that was passed down from the parent. By setting the default state to hidden, React will still render the component immediately, but it won't be visible until the state has changed. Then, you can set up componentWillMount
to call a function to show it after the duration that was passed via props.
var Child = React.createClass({
getInitialState : function () {
return({hidden : "hidden"});
},
componentWillMount : function () {
var that = this;
setTimeout(function() {
that.show();
}, that.props.wait);
},
show : function () {
this.setState({hidden : ""});
},
render : function () {
return (
<div className={this.state.hidden}>
<p>Child</p>
</div>
)
}
});
Then, in the Parent component, all you would need to do is pass the duration you want a Child to wait before displaying it.
var Parent = React.createClass({
render : function () {
return (
<div className="parent">
<p>Parent</p>
<div className="child-list">
<Child wait={1000} />
<Child wait={3000} />
<Child wait={5000} />
</div>
</div>
)
}
});
System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
function rgb(...values){
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0'+val : val);
}, '').toUpperCase();
}
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
There are two steps here:
X$newdate <- strptime(as.character(X$date), "%d/%m/%Y")
Now the newdate
column should be of type Date
.
format()
or strftime()
:format(X$newdate, "%Y-%m-%d")
A more complete example:
R> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"),
+ mid=c(0.8378,0.8457,0.8147))
R> nzd
date mid
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
R> nzd$newdate <- strptime(as.character(nzd$date), "%d/%m/%Y")
R> nzd$txtdate <- format(nzd$newdate, "%Y-%m-%d")
R> nzd
date mid newdate txtdate
1 31/08/2011 0.8378 2011-08-31 2011-08-31
2 31/07/2011 0.8457 2011-07-31 2011-07-31
3 30/06/2011 0.8147 2011-06-30 2011-06-30
R>
The difference between columns three and four is the type: newdate
is of class Date
whereas txtdate
is character.
I recently hit the same error. Some digging brought up this: http://support.microsoft.com/kb/815645
Basically, if you have spaces in the path of the .lib, that's bad. Don't know if that's what's happening for you, but seems reasonably possible.
The fix is either 1) put the lib reference in "quotes", or 2) add the lib's path to your Library Directories (Configuration Properties >> VC++ Directories).
It has been done there : http://www.jezra.net/projects/pageplayer
Add a width to the .child
elements. I personally would use percentages on the margin-left
if you want to have it always 4 per row.
.child {
display: inline-block;
background: blue;
margin: 10px 0 0 2%;
flex-grow: 1;
height: 100px;
width: calc(100% * (1/4) - 10px - 1px);
}
heres a DOM solution
myInput=document.getElementById("myinput");
oldHtml=myInput.outerHTML;
text=myInput.value;
newHtml=oldHtml.replace("password","text");
myInput.outerHTML=newHtml;
myInput=document.getElementById("myinput");
myInput.value=text;
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
from openpyxl import load_workbook
sheets = load_workbook(excel_file, read_only=True).sheetnames
For a 5MB Excel file I'm working with, load_workbook
without the read_only
flag took 8.24s. With the read_only
flag it only took 39.6 ms. If you still want to use an Excel library and not drop to an xml solution, that's much faster than the methods that parse the whole file.
I had major trouble getting this to work in RCx releases of angular2. The Location package has moved, and running location.go() inside constructor() wont work. It needs to be ngOnInit() or later in the lifecycle. Here is some example code:
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
constructor( private location: Location )
{}
ngOnInit()
{
this.location.go( '/example;example_param=917' );
}
}
Here are the angular resources on the matter: https://angular.io/docs/ts/latest/api/common/index/Location-class.html https://angular.io/docs/ts/latest/api/common/index/LocationStrategy-class.html