When you set 64-bit the resulting binary is a "Fat" binary, which contains all three Mach-O images bundled with a thin fat header. You can see that using otool or jtool. You can check out some fat binaries included as part of the iOS 7.0 SDK, for example the AVFoundation Framework, like so:
% cd /Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.0\ \(11A465\)/Symbols/System/Library/Frameworks/AVFoundation.framework/
%otool -V -f AVFoundation 9:36
Fat headers
fat_magic FAT_MAGIC
nfat_arch 3
architecture arm64 # The 64-bit version (A7)
cputype CPU_TYPE_ARM64
cpusubtype CPU_SUBTYPE_ARM64_ALL
capabilities 0x0
offset 16384
size 2329888
align 2^14 (16384)
architecture armv7 # A5X - packaged after the arm64version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7
capabilities 0x0
offset 2359296
size 2046336
align 2^14 (16384)
architecture armv7s # A6 - packaged after the armv7 version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7S
capabilities 0x0
offset 4407296
size 2046176
align 2^14 (16384)
As for the binary itself, it uses the ARM64 bit instruction set, which is (mostly compatible with 32-bit, but) a totally different instruction set. This is especially important for graphics program (using NEON instructions and registers). Likewise, the CPU has more registers, which makes quite an impact on program speed. There's an interesting discussion in http://blogs.barrons.com/techtraderdaily/2013/09/19/apple-the-64-bit-question/?mod=yahoobarrons on whether or not this makes a difference; benchmarking tests have so far clearly indicated that it does.
Using otool -tV will dump the assembly (if you have XCode 5 and later), and then you can see the instruction set differences for yourself. Most (but not all) developers will remain agnostic to the changes, as for the most part they do not directly affect Obj-C (CG* APIs notwithstanding), and have to do more with low level pointer handling. The compiler will work its magic and optimizations.
Paste in the url of the page and click debug. If your site is using url aliases make sure you are using the same url as Facebook is using for the page you are sharing (example: in Drupal use the node/* path instead of the alias if the page is shared via that url).
It is possible and you don't need to code it on your own.
Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...
Its just done for you with the application Nostalk from Android Market. Just give it a try ...
Depending on which environment you are using to run the emulator, check the logs to see how the emulator is started. Mine is started as:
C:\Users\johan\AppData\Local\Android\Sdk\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_23
Then you add the -http-proxy option, in my case:
C:\Users\johan\AppData\Local\Android\Sdk\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_23 -http-proxy 192.168.0.22:8888
CGRect
Can be simply created using an instance of a CGPoint
or CGSize
, thats given below.
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// Or
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
Or if we want to specify each value in CGFloat
or Double
or Int
, we can use this method.
let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int
CGPoint
Can be created like this.
let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int
CGSize
Can be created like this.
let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int
Also size and point with 0 as the values, it can be done like this.
let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero
CGRectZero
& CGPointZero
replaced with CGRect.zero
& CGPoint.zero
in Swift 3.0
.
You could implement it like this:
@SuppressWarnings("unchecked")
public <T extends Animal> T callFriend(String name) {
return (T)friends.get(name);
}
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)
The return type will be inferred from the caller. However, note the @SuppressWarnings
annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions
at runtime.
Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:
jerry.<Dog>callFriend("spike").bark();
While this may be a little nicer than casting, you are probably better off giving the Animal
class an abstract talk()
method, as David Schmitt said.
The following worked for me:
It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").
More can be found here:
In Android Studio
Go to edit Configuration .
Select the app.
choose the lunch Activity path.
apply, OK.
Thanks!!
I like bobince's answer:
placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)
But I noticed this:
placeholders= ', '.join(placeholder for unused in l)
Can be replaced with:
placeholders= ', '.join(placeholder*len(l))
I find this more direct if less clever and less general. Here l
is required to have a length (i.e. refer to an object that defines a __len__
method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:
placeholders= ', '.join([placeholder]*len(l))
Wouldn't you just change:
numero = stmt.executeUpdate(query);
to:
numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
Take a look at the documentation for the JDBC Statement
interface.
Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero
variable is completely irrelevant and its value is never read after it is set.
You could use std::numeric_limits<size_t>::max()
for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector
has size equal to std::numeric_limits<size_t>::max()
, then maximum allowed index will be (std::numeric_limits<size_t>::max()-1)
, since elements counted from 0.
This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:
::-webkit-scrollbar {
width: 2em;
height: 2em
}
::-webkit-scrollbar-button {
background: #ccc
}
::-webkit-scrollbar-track-piece {
background: #888
}
::-webkit-scrollbar-thumb {
background: #eee
}?
References:
To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
@with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
tomaterial = models.ForeignKey(Material, related_name = 'tomaterial')
frommaterial = models.ForeignKey(Material, related_name = 'frommaterial')
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
So when you will have to access this data you only can use related name
bom = material.tomaterial.all().order_by('-creation_time')
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
where c.FullName.Contains("string")
private Session.StatusCallback statusCallback = new SessionStatusCallback();
logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Session.openActiveSession(this, true, statusCallback);
}
});
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
session.closeAndClearTokenInformation();
}
}
I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.
var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
This was from the FAQs for Cookie.js
You can use javax.xml.bind.DatatypeConverter
class
DatatypeConverter.printDateTime
&
DatatypeConverter.parseDateTime
For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
I would assume that one might want a solution that produces a widely useable base64 URI. Please visit data:text/plain;charset=utf-8;base64,4pi44pi54pi64pi74pi84pi+4pi/
to see a demonstration (copy the data uri, open a new tab, paste the data URI into the address bar, then press enter to go to the page). Despite the fact that this URI is base64-encoded, the browser is still able to recognize the high code points and decode them properly. The minified encoder+decoder is 1058 bytes (+Gzip?589 bytes)
!function(e){"use strict";function h(b){var a=b.charCodeAt(0);if(55296<=a&&56319>=a)if(b=b.charCodeAt(1),b===b&&56320<=b&&57343>=b){if(a=1024*(a-55296)+b-56320+65536,65535<a)return d(240|a>>>18,128|a>>>12&63,128|a>>>6&63,128|a&63)}else return d(239,191,189);return 127>=a?inputString:2047>=a?d(192|a>>>6,128|a&63):d(224|a>>>12,128|a>>>6&63,128|a&63)}function k(b){var a=b.charCodeAt(0)<<24,f=l(~a),c=0,e=b.length,g="";if(5>f&&e>=f){a=a<<f>>>24+f;for(c=1;c<f;++c)a=a<<6|b.charCodeAt(c)&63;65535>=a?g+=d(a):1114111>=a?(a-=65536,g+=d((a>>10)+55296,(a&1023)+56320)):c=0}for(;c<e;++c)g+="\ufffd";return g}var m=Math.log,n=Math.LN2,l=Math.clz32||function(b){return 31-m(b>>>0)/n|0},d=String.fromCharCode,p=atob,q=btoa;e.btoaUTF8=function(b,a){return q((a?"\u00ef\u00bb\u00bf":"")+b.replace(/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g,h))};e.atobUTF8=function(b,a){a||"\u00ef\u00bb\u00bf"!==b.substring(0,3)||(b=b.substring(3));return p(b).replace(/[\xc0-\xff][\x80-\xbf]*/g,k)}}(""+void 0==typeof global?""+void 0==typeof self?this:self:global)
Below is the source code used to generate it.
var fromCharCode = String.fromCharCode;
var btoaUTF8 = (function(btoa, replacer){"use strict";
return function(inputString, BOMit){
return btoa((BOMit ? "\xEF\xBB\xBF" : "") + inputString.replace(
/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer
));
}
})(btoa, function(nonAsciiChars){"use strict";
// make the UTF string into a binary UTF-8 encoded string
var point = nonAsciiChars.charCodeAt(0);
if (point >= 0xD800 && point <= 0xDBFF) {
var nextcode = nonAsciiChars.charCodeAt(1);
if (nextcode !== nextcode) // NaN because string is 1 code point long
return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {
point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;
if (point > 0xffff)
return fromCharCode(
(0x1e/*0b11110*/<<3) | (point>>>18),
(0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),
(0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
(0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
);
} else return fromCharCode(0xef, 0xbf, 0xbd);
}
if (point <= 0x007f) return nonAsciiChars;
else if (point <= 0x07ff) {
return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f));
} else return fromCharCode(
(0xe/*0b1110*/<<4) | (point>>>12),
(0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),
(0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)
);
});
Then, to decode the base64 data, either HTTP get the data as a data URI or use the function below.
var clz32 = Math.clz32 || (function(log, LN2){"use strict";
return function(x) {return 31 - log(x >>> 0) / LN2 | 0};
})(Math.log, Math.LN2);
var fromCharCode = String.fromCharCode;
var atobUTF8 = (function(atob, replacer){"use strict";
return function(inputString, keepBOM){
inputString = atob(inputString);
if (!keepBOM && inputString.substring(0,3) === "\xEF\xBB\xBF")
inputString = inputString.substring(3); // eradicate UTF-8 BOM
// 0xc0 => 0b11000000; 0xff => 0b11111111; 0xc0-0xff => 0b11xxxxxx
// 0x80 => 0b10000000; 0xbf => 0b10111111; 0x80-0xbf => 0b10xxxxxx
return inputString.replace(/[\xc0-\xff][\x80-\xbf]*/g, replacer);
}
})(atob, function(encoded){"use strict";
var codePoint = encoded.charCodeAt(0) << 24;
var leadingOnes = clz32(~codePoint);
var endPos = 0, stringLen = encoded.length;
var result = "";
if (leadingOnes < 5 && stringLen >= leadingOnes) {
codePoint = (codePoint<<leadingOnes)>>>(24+leadingOnes);
for (endPos = 1; endPos < leadingOnes; ++endPos)
codePoint = (codePoint<<6) | (encoded.charCodeAt(endPos)&0x3f/*0b00111111*/);
if (codePoint <= 0xFFFF) { // BMP code point
result += fromCharCode(codePoint);
} else if (codePoint <= 0x10FFFF) {
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
result += fromCharCode(
(codePoint >> 10) + 0xD800, // highSurrogate
(codePoint & 0x3ff) + 0xDC00 // lowSurrogate
);
} else endPos = 0; // to fill it in with INVALIDs
}
for (; endPos < stringLen; ++endPos) result += "\ufffd"; // replacement character
return result;
});
The advantage of being more standard is that this encoder and this decoder are more widely applicable because they can be used as a valid URL that displays correctly. Observe.
(function(window){_x000D_
"use strict";_x000D_
var sourceEle = document.getElementById("source");_x000D_
var urlBarEle = document.getElementById("urlBar");_x000D_
var mainFrameEle = document.getElementById("mainframe");_x000D_
var gotoButton = document.getElementById("gotoButton");_x000D_
var parseInt = window.parseInt;_x000D_
var fromCodePoint = String.fromCodePoint;_x000D_
var parse = JSON.parse;_x000D_
_x000D_
function unescape(str){_x000D_
return str.replace(/\\u[\da-f]{0,4}|\\x[\da-f]{0,2}|\\u{[^}]*}|\\[bfnrtv"'\\]|\\0[0-7]{1,3}|\\\d{1,3}/g, function(match){_x000D_
try{_x000D_
if (match.startsWith("\\u{"))_x000D_
return fromCodePoint(parseInt(match.slice(2,-1),16));_x000D_
if (match.startsWith("\\u") || match.startsWith("\\x"))_x000D_
return fromCodePoint(parseInt(match.substring(2),16));_x000D_
if (match.startsWith("\\0") && match.length > 2)_x000D_
return fromCodePoint(parseInt(match.substring(2),8));_x000D_
if (/^\\\d/.test(match)) return fromCodePoint(+match.slice(1));_x000D_
}catch(e){return "\ufffd".repeat(match.length)}_x000D_
return parse('"' + match + '"');_x000D_
});_x000D_
}_x000D_
_x000D_
function whenChange(){_x000D_
try{ urlBarEle.value = "data:text/plain;charset=UTF-8;base64," + btoaUTF8(unescape(sourceEle.value), true);_x000D_
} finally{ gotoURL(); }_x000D_
}_x000D_
sourceEle.addEventListener("change",whenChange,{passive:1});_x000D_
sourceEle.addEventListener("input",whenChange,{passive:1});_x000D_
_x000D_
// IFrame Setup:_x000D_
function gotoURL(){mainFrameEle.src = urlBarEle.value}_x000D_
gotoButton.addEventListener("click", gotoURL, {passive: 1});_x000D_
function urlChanged(){urlBarEle.value = mainFrameEle.src}_x000D_
mainFrameEle.addEventListener("load", urlChanged, {passive: 1});_x000D_
urlBarEle.addEventListener("keypress", function(evt){_x000D_
if (evt.key === "enter") evt.preventDefault(), urlChanged();_x000D_
}, {passive: 1});_x000D_
_x000D_
_x000D_
var fromCharCode = String.fromCharCode;_x000D_
var btoaUTF8 = (function(btoa, replacer){_x000D_
"use strict";_x000D_
return function(inputString, BOMit){_x000D_
return btoa((BOMit?"\xEF\xBB\xBF":"") + inputString.replace(_x000D_
/[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, replacer_x000D_
));_x000D_
}_x000D_
})(btoa, function(nonAsciiChars){_x000D_
"use strict";_x000D_
// make the UTF string into a binary UTF-8 encoded string_x000D_
var point = nonAsciiChars.charCodeAt(0);_x000D_
if (point >= 0xD800 && point <= 0xDBFF) {_x000D_
var nextcode = nonAsciiChars.charCodeAt(1);_x000D_
if (nextcode !== nextcode) { // NaN because string is 1code point long_x000D_
return fromCharCode(0xef/*11101111*/, 0xbf/*10111111*/, 0xbd/*10111101*/);_x000D_
}_x000D_
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae_x000D_
if (nextcode >= 0xDC00 && nextcode <= 0xDFFF) {_x000D_
point = (point - 0xD800) * 0x400 + nextcode - 0xDC00 + 0x10000;_x000D_
if (point > 0xffff) {_x000D_
return fromCharCode(_x000D_
(0x1e/*0b11110*/<<3) | (point>>>18),_x000D_
(0x2/*0b10*/<<6) | ((point>>>12)&0x3f/*0b00111111*/),_x000D_
(0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
(0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
);_x000D_
}_x000D_
} else {_x000D_
return fromCharCode(0xef, 0xbf, 0xbd);_x000D_
}_x000D_
}_x000D_
if (point <= 0x007f) { return inputString; }_x000D_
else if (point <= 0x07ff) {_x000D_
return fromCharCode((0x6<<5)|(point>>>6), (0x2<<6)|(point&0x3f/*00111111*/));_x000D_
} else {_x000D_
return fromCharCode(_x000D_
(0xe/*0b1110*/<<4) | (point>>>12),_x000D_
(0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/),_x000D_
(0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/)_x000D_
);_x000D_
}_x000D_
});_x000D_
setTimeout(whenChange, 0);_x000D_
})(window);
_x000D_
img:active{opacity:0.8}
_x000D_
<center>_x000D_
<textarea id="source" style="width:66.7vw">Hello \u1234 W\186\0256ld!_x000D_
Enter text into the top box. Then the URL will update automatically._x000D_
</textarea><br />_x000D_
<div style="width:66.7vw;display:inline-block;height:calc(25vw + 1em + 6px);border:2px solid;text-align:left;line-height:1em">_x000D_
<input id="urlBar" style="width:calc(100% - 1em - 13px)" /><img id="gotoButton" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAeCAMAAADqx5XUAAAAclBMVEX///9NczZ8e32ko6fDxsU/fBoSQgdFtwA5pAHVxt+7vLzq5ex23y4SXABLiiTm0+/c2N6DhoQ6WSxSyweVlZVvdG/Uz9aF5kYlbwElkwAggACxs7Jl3hX07/cQbQCar5SU9lRntEWGum+C9zIDHwCGnH5IvZAOAAABmUlEQVQoz7WS25acIBBFkRLkIgKKtOCttbv//xdDmTGZzHv2S63ltuBQQP4rdRiRUP8UK4wh6nVddQwj/NtDQTvac8577zTQb72zj65/876qqt7wykU6/1U6vFEgjE1mt/5LRqrpu7oVsn0sjZejMfxR3W/yLikqAFcUx93YxLmZGOtElmEu6Ufd9xV3ZDTGcEvGLbMk0mHHlUSvS5svCwS+hVL8loQQyfpI1Ay8RF/xlNxcsTchGjGDIuBG3Ik7TMyNxn8m0TSnBAK6Z8UZfp3IbAonmJvmsEACum6aNv7B0CnvpezDcNhw9XWsuAr7qnRg6dABmeM4dTgn/DZdXWs3LMspZ1KDMt1kcPJ6S1icWNp2qaEmjq6myx7jbQK3VKItLJaW5FR+cuYlRhYNKzGa9vF4vM5roLW3OSVjkmiGJrPhUq301/16pVKZRGFYWjTP50spTxBN5Z4EKnSonruk+n4tUokv1aJSEl/MLZU90S3L6/U6o0J142iQVp3HcZxKSo8LfkNRCtJaKYFSRX7iaoAAUDty8wvWYR6HJEepdwAAAABJRU5ErkJggg==" style="width:calc(1em + 4px);line-height:1em;vertical-align:-40%;cursor:pointer" />_x000D_
<iframe id="mainframe" style="width:66.7vw;height:25vw" frameBorder="0"></iframe>_x000D_
</div>_x000D_
</center>
_x000D_
In addition to being very standardized, the above code snippets are also very fast. Instead of an indirect chain of succession where the data has to be converted several times between various forms (such as in Riccardo Galli's response), the above code snippet is as direct as performantly possible. It uses only one simple fast String.prototype.replace
call to process the data when encoding, and only one to decode the data when decoding. Another plus is that (especially for big strings), String.prototype.replace
allows the browser to automatically handle the underlying memory management of resizing the string, leading a significant performance boost especially in evergreen browsers like Chrome and Firefox that heavily optimize String.prototype.replace
. Finally, the icing on the cake is that for you latin script exclusivo users, strings which don't contain any code points above 0x7f are extra fast to process because the string remains unmodified by the replacement algorithm.
I have created a github repository for this solution at https://github.com/anonyco/BestBase64EncoderDecoder/
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
Chrome appears to have bug renegotiating the device authentication. You can try disabling USB Debugging and enabling it again. Sometimes you'll get a pop-up asking you to trust your computer key again.
Or you can go to your Android SDK and run adb devices
which will force a renegotiation.
After either (or both), Chrome should start working.
Just want to point out you do not need to specify all dimensions of the array.
The leftmost dimension can be 'guessed' by the compiler.
#include <stdio.h>
int main(void) {
int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
printf("sizeof arr is %d bytes\n", (int)sizeof arr);
printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
return 0;
}
It look's as if you forgot to activate you virtual environment
try running python3 -m venv venv
or if you already have virtual environment
set up try to activate it by running source venv/bin/activate
As already explained in other answers, when in Private Browsing mode Safari will always throw this exception when trying to save data with localStorage.setItem()
.
To fix this I wrote a fake localStorage that mimics localStorage, both methods and events.
Fake localStorage: https://gist.github.com/engelfrost/fd707819658f72b42f55
This is probably not a good general solution to the problem. This was a good solution for my scenario, where the alternative would be major re-writes to an already existing application.
I know only Oracle databases, no other ones, and I can tell that Foreign Keys are essential for maintaining data integrity. Prior to inserting data, a data structure needs to be made, and be made correctlty. When that is done - and thus all primary AND foreign keys are created - the work is done !
Meaning : orphaned rows ? No. Never seen that in my life. Unless a bad programmer forgot the foreign key, or if he implemented that on another level. Both are - in context of Oracle - huge mistakes, which will lead to data duplication, orphan data, and thus : data corruption. I can't imagine a database without FK enforced. It looks like chaos to me. It's a bit like the Unix permission system : imagine that everybody is root. Think of the chaos.
Foreign Keys are essential, just like Primary Keys. It's like saying : what if we removing Primary Keys ? Well, total chaos is going to happen. That's what. You may not move the primary or foreign key responsibility to the programming level, it must be at the data level.
Drawbacks ? Yes, absolutely ! Because on insert, a lot more checks are going to be happening. But, if data integrity is more important than performance, it's a no-brainer. The problem with performance on Oracle is more related to indexes, which come with PK and FK's.
instead of using add() we can use addall()
{ seeAlso.addall(groupDn); }
add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.
PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.
Use mb_convert_encoding to convert an ASCII to UTF-8. More info here
$string = "chárêctërs";
print(mb_detect_encoding ($string));
$string = mb_convert_encoding($string, "UTF-8");
print(mb_detect_encoding ($string));
I've found out that somethimes one ScrollView regains focus and the other loses focus. You can prevent that, by only granting one of the scrollView focus:
scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
scrollView1.setAdapter(adapter);
scrollView1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:
Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
<div style="width:800px;">
now really long text like this can be put in the text area and it will really <br/>
look and act more like a real text area bla bla bla <br/>
</div>
</div>
Try this:
USE master;
GO;
GRANT ADMINISTER BULK OPERATIONS TO shira;
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
You can go settings, select packages and type atom-runner
there if your browser can't open this link.
To run your code do Alt+R if you're using Windows
in Atom
.
You could us the 'net use' command:
var p = System.Diagnostics.Process.Start("net.exe", "use K: \\\\Server\\path");
var isCompleted = p.WaitForExit(5000);
If that does not work in a service, try the Winapi and PInvoke WNetAddConnection2
Edit: Obviously I misunderstood you - you can not change the sourcecode of the service, right? In that case I would follow the suggestion by mdb, but with a little twist: Create your own service (lets call it mapping service) that maps the drive and add this mapping service to the dependencies for the first (the actual working) service. That way the working service will not start before the mapping service has started (and mapped the drive).
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
I usually use XmlDocument
for this. The interface is pretty straight forward:
var doc = new XmlDocument();
doc.LoadXml(xmlString);
You can access nodes similar to a dictionary:
var tasks = doc["Tasks"];
and loop over all children of a node.
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[]
.
However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:
string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);
This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)
I had the same problem once this is how I solved it.
Suppose I want 12 delays with an interval of 2 secs
function animate(i){
myVar=setTimeout(function(){
alert(i);
if(i==12){
clearTimeout(myVar);
return;
}
animate(i+1)
},2000)
}
var i=1; //i is the start point 1 to 12 that is
animate(i); //1,2,3,4..12 will be alerted with 2 sec delay
This error is because
argv # which is argument variable that is holding the variables that you pass with a call to the script.
so now instead
Python abc.py
do
python abc.py yourname {pass the variable that you made to store argv}
You can use .toString()
to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c
.
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
This works well for console in debug mode
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
As described in this link http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html
Declare in dimen.xml
<item name="my_float_value" type="dimen" format="float">9.52</item>
Referencing from xml
@dimen/my_float_value
Referencing from java
TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();
Below are some of the way by which you can create a link button in MVC.
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
@Html.Action("Action", "Controller", new { area = "AreaName" })
@Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
How about Freebase? I think they have an API available, too.
I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'
log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
Hierarchy hierarchy = (Hierarchy)repository;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
patternLayout.ActivateOptions();
RollingFileAppender roller = new RollingFileAppender();
roller.AppendToFile = true;
roller.File = "Log_";
roller.DatePattern = "MM-dd-yyyy'.log'";
roller.Layout = patternLayout;
roller.MaxFileSize = 1024*1024*10;
roller.MaxSizeRollBackups = 10;
roller.StaticLogFileName = false;
roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
I had a problem with sending a request with multiple parameters.
I've solved it by sending a class, with the old parameters as properties.
<form action="http://localhost:12345/api/controller/method" method="post">
<input type="hidden" name="name1" value="value1" />
<input type="hidden" name="name2" value="value2" />
<input type="submit" name="submit" value="Submit" />
</form>
Model class:
public class Model {
public string Name1 { get; set; }
public string Name2 { get; set; }
}
Controller:
public void method(Model m) {
string name = m.Name1;
}
Steps to follow:
Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.
Insert a new module. From the menu: Insert -> Module (Don't skip this!).
Create a Public
function. Example:
Public Function findArea(ByVal width as Double, _
ByVal height as Double) As Double
' Return the area
findArea = width * height
End Function
Then use it in any cell like you would any other function: =findArea(B12,C12)
.
metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:
<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>
409 Conflict
could be an acceptable solution.
According to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
The doc continues with an example:
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.
If it is, I will return "Error: The string is already in the database", 409
.
I believe this is what the OP wanted: an error code suitable for when the data does not pass the server's criteria.
Use a generator function to generate an iterator.
def foo_gen():
n = 0
while True:
n+=1
yield n
Then use it like
foo = foo_gen().next
for i in range(0,10):
print foo()
If you want an upper limit:
def foo_gen(limit=100000):
n = 0
while n < limit:
n+=1
yield n
If the iterator terminates (like the example above), you can also loop over it directly, like
for i in foo_gen(20):
print i
Of course, in these simple cases it's better to use xrange :)
Here is the documentation on the yield statement.
long start = System.currentTimeMillis();
counter.countPrimes(1000000);
long end = System.currentTimeMillis();
System.out.println("Took : " + ((end - start) / 1000));
UPDATE
An even more accurate solution would be:
final long start = System.nanoTime();
counter.countPrimes(1000000);
final long end = System.nanoTime();
System.out.println("Took: " + ((end - start) / 1000000) + "ms");
System.out.println("Took: " + (end - start)/ 1000000000 + " seconds");
We can use both for the same way, and they are only different in the performance.
IQueryable only executes against the database in an efficient way. It means that it creates an entire select query and only gets the related records.
For example, we want to take the top 10 customers whose name start with ‘Nimal’. In this case the select query will be generated as select top 10 * from Customer where name like ‘Nimal%’
.
But if we used IEnumerable, the query would be like select * from Customer where name like ‘Nimal%’
and the top ten will be filtered at the C# coding level (it gets all the customer records from the database and passes them into C#).
In my case it was because of an invisible character at the beginning of the path:
Maybe It can be perfect example for Android, For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
# Pygame Example
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('IBM Emulator')
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)
textRectObj = textSurfaceObj.get_rect()
textRectObj = (10, 10)
try:
while True: # main loop
DISPLAYSURF.fill(BLACK)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
except SystemExit:
pass
This fixed my issue:
Go to terminal shell and type mongo
.
Then type use db_name
.
Then type:
db.createUser(
{
user: "mongodb",
pwd: "dogmeatsubparflavour1337",
roles: [ { role: "dbOwner", db: "db_name" } ]
}
)
Also try: db.getUsers()
Quick sample:
const MongoClient = require('mongodb').MongoClient;
// MongoDB Connection Info
const url = 'mongodb://mongodb:[email protected]:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options
// Use Connect Method to connect to the Server
MongoClient.connect(url)
.then((db) => {
console.log(db);
console.log('Casually connected correctly to server.');
// Be careful with db.close() when working asynchronously
db.close();
})
.catch((error) => {
console.log(error);
});
I developed a library for this usecase: https://github.com/sunnykgupta/jsLogger
Features:
log
, warn
, error
, info
.Is open for modifications and will be updated whenever new suggestions come up.
I was prompted to login to our TFS server via Visual Studio, so I used my SU account which is typically required for server access. This led to some issues, and I ended up mapping to a different folder, not realizing I had just duplicated all my stuff. At some point, Visual Studio reverted back to my regular user, I "lost" pending changes, and noticed that new pending changes were placed by in my old mapping.
When I would try to remap to the new location (that the SU account was linked to) in an attempt to recover my pending changes, it would tell me it was already mapped to the SU, and I couldn't do that, but had no way of removing the map! Show remote workspaces, removing all workspaces via command line, etc revealed nothing. I then thought "what if it's actually linked to the SU user account on my computer, not the domain." I logged in as my SU locally, and sure enough, there was a workspace all setup for that user. I removed the mapping, and was able to go back to my regular user and remap without issue.
Moral of the story, perhaps another user is logged in on the same machine, which isn't visible from the currently logged in user, thus you cannot remove or even see the mappings.
This worked for me:
If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.
So, write the necessary objects to file again if a class is modified and recompiled.
PS: This is NOT a solution; was meant to be a workaround.
for Bootstrap 3.+ , I'd use following CSS to fix navbar-fixed-top and the anchor jump overlapped issue based on https://github.com/twbs/bootstrap/issues/1768
/* fix fixed-bar */
body { padding-top: 40px; }
@media screen and (max-width: 768px) {
body { padding-top: 40px; }
}
/* fix fixed-bar jumping to in-page anchor issue */
*[id]:before {
display: block;
content: " ";
margin-top: -75px;
height: 75px;
visibility: hidden;
}
One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text
[Display(Name = "Wild and Crazy")]
public string WildAndCrazyProperty { get; set; }
"Wild and Crazy" shows up consistently wherever you use the property in your application.
Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example
You must use plt.show()
at the end in order to see the plot
An abstract class can be used instead of an interface (in C# 7.3).
// Like interface
abstract class IIO
{
public virtual async Task<string> DoOperation(string Name)
{
throw new NotImplementedException(); // throwing exception
// return await Task.Run(() => { return ""; }); // or empty do
}
}
// Implementation
class IOImplementation : IIO
{
public override async Task<string> DoOperation(string Name)
{
return await await Task.Run(() =>
{
if(Name == "Spiderman")
return "ok";
return "cancel";
});
}
}
This works but the value I get is multiplied times the screen density factor
(1.5 for hdpi, 2.0 for xhdpi, etc).
I think it is good to get the value as per resolution but if you not want to do this give this in px.......
Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.
The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels.
You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.
I think it is good to change the value as per resolution but if you not want to do this give this in px.......
refer this link
as per this
dp
Density-independent Pixels - An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down.
The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.
px
Pixels - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.
I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID
attribute. To support older browsers, you'll need to change:
<div id="timeline" name="timeline" ...>
To the old format:
<a name="timeline" />
You'll then be able to navigate to /academics/page.html#timeline
and jump right to that section.
Also, check out this similar question.
PHP will work only on the .php
file extension.
If you are on Apache you can also set, in your httpd.conf
file, the extensions for PHP. You'll have to find the line:
AddType application/x-httpd-php .php .html
^^^^^
and add how many extensions, that should be read with the PHP interpreter, as you want.
Here's my setup: I am on Ubuntu 9.10.
Now, Here's what I did.
Create an xml file "myapp.xml" (i guess it must have the same name as the name of the folder in step 2) inside /etc/tomcat6/Catalina/localhost with the following contents.
< Context path="/myapp" docBase="/usr/share/tomcat6-myapp/myapp" />
This xml is called the 'Deployment Descriptor' which Tomcat reads and automatically deploys your app named "myapp".
Now go to http://localhost:8080/myapp in your browser - the index.html gets picked up by tomcat and is shown.
I hope this helps!
Try using the "%h"
modifier:
scanf("%hu", &length);
^
ISO/IEC 9899:201x - 7.21.6.1-7
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO
, foo
, and "foo"
are considered the same by PostgreSQL, but "Foo"
and "FOO"
are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
You may get ORA-01031: insufficient privileges
instead of ORA-00942: table or view does not exist
when you have at least one privilege on the table, but not the necessary privilege.
Create schemas
SQL> create user schemaA identified by schemaA;
User created.
SQL> create user schemaB identified by schemaB;
User created.
SQL> create user test_user identified by test_user;
User created.
SQL> grant connect to test_user;
Grant succeeded.
Create objects and privileges
It is unusual, but possible, to grant a schema a privilege like DELETE without granting SELECT.
SQL> create table schemaA.table1(a number);
Table created.
SQL> create table schemaB.table2(a number);
Table created.
SQL> grant delete on schemaB.table2 to test_user;
Grant succeeded.
Connect as TEST_USER and try to query the tables
This shows that having some privilege on the table changes the error message.
SQL> select * from schemaA.table1;
select * from schemaA.table1
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select * from schemaB.table2;
select * from schemaB.table2
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL>
(IN @brugernavn varchar(64)**)**,IN @password varchar(64))
The problem is the )
You could create a new List
and addAll()
of your other List
s to it. Then return an unmodifiable list with Collections.unmodifiableList()
.
A different take on this question, which might help someone:
I came here because I was debugging in Visual Studio on Windows, and I got confused about all this /
vs \\
discussion (it really should not matter in most cases).
For me, the problem was: the "current directory" was not set to what I wanted in Visual Studio. It defaults to the directory of the executable (depending on how you set up your project).
Change it via: Right-click the solution -> Properties -> Working Directory
I only mention it because the question seems Windows-centric, which generally also means VisualStudio-centric, which tells me this hint might be relevant (:
Actually you can do this with:
ssl off;
This solved my problem in using nginxvhosts; now I am able to use both SSL and plain HTTP. Works even with combined ports.
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
can be done like this too.
let data_array = [];
let my_object = {};
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
data_array.push(my_object);
Try adding the following line at the top of your python script.
# _*_ coding:utf-8 _*_
Use this command to trigger the notification center notification from the terminal.
osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
use g++
instead of gcc
.
A checkbox input is a native element served to implement toggle functionality, we can use that to our benefit.
Utilize the :checked
pseudo class - attach it to a pseudo element of a checkbox (since you can't really affect the background of the input
itself), and change its background accordingly.
input[type="checkbox"]:before {
content: url('images/icon.png');
display: block;
width: 100px;
height: 100px;
}
input[type="checkbox"]:checked:before {
content: url('images/another-icon.png');
}
Here's a full working demo on jsFiddle to illustrate the approach.
This is a bit cumbersome, and we could make some changes to clean up unnecessary stuff; as we're not really applying a background image, but instead setting the element's content
, we can omit the pseudo elements and set it directly on the checkbox.
Admittedly, they serve no real purpose here but to mask the native rendering of the checkbox. We could simply remove them, but that would result in a FOUC in best cases, or if we fail to fetch the image, it will simply show a huge checkbox.
Enters the appearance
property:
The
(-moz-)appearance
CSS property is used ... to display an element using a platform-native styling based on the operating system's theme.
we can override the platform-native styling by assigning appearance: none
and bypass that glitch altogether (we would have to account for vendor prefixes, naturally, and the prefix-free form is not supported anywhere, at the moment). The selectors are then simplified, and the code is more robust.
input[type="checkbox"] {
content: url('images/black.cat');
display: block;
width: 200px;
height: 200px;
-webkit-appearance: none;
}
input[type="checkbox"]:checked {
content: url('images/white.cat');
}
Again, a live demo of the refactored version is on jsFiddle.
Note: this only works on webkit for now, I'm trying to have it fixed for gecko engines also. Will post the updated version once I do.
there is one difference in behavior between [] and list() as example below shows. we need to use list() if we want to have the list of numbers returned, otherwise we get a map object! No sure how to explain it though.
sth = [(1,2), (3,4),(5,6)]
sth2 = map(lambda x: x[1], sth)
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
sth2 = [map(lambda x: x[1], sth)]
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
type(sth2) # list
type(sth2[0]) # map
sth2 = list(map(lambda x: x[1], sth))
print(sth2) #[2, 4, 6]
type(sth2) # list
type(sth2[0]) # int
Android follows the same naming conventions like Java,
Naming Conventions
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names:
Domain Name Package Name Prefix
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name
If you want to list folders and files like graphical directory tree, you should use tree command.
tree /f
There are various options for display format or ordering.
Check example output.
Answering late. Hope it help someone.
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Try to avoid formatting in your query. You should return your data in a raw format and let the receiving application (e.g. a reporting service or end user app) do the formatting, i.e. rounding and so on.
Formatting the data in the server makes it harder (or even impossible) for you to further process your data. You usually want export the table or do some aggregation as well, like sum, average etc. As the numbers arrive as strings (varchar), there is usually no easy way to further process them. Some report designers will even refuse to offer the option to aggregate these 'numbers'.
Also, the end user will see the country specific formatting of the server instead of his own PC.
Also, consider rounding problems. If you round the values in the server and then still do some calculations (supposing the client is able to revert the number-strings back to a number), you will end up getting wrong results.
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
Use:
<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>
A PowerShell script based on @Mithrl's answer
# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date
mkdir -Force $PWD\env_exports | Out-Null
regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Try this
This is the simplest way to ask for permission in Marshmallow version.
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
//TO do here if permission is granted by user
}
else
{
//ask for permission if user didnot given
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
}
Note:- Don't forget to add this same permission in manifest file also
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Second Method Code for checking the permission is granted or not?
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, 1);
And override the method
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// grantResult[0] means it will check for the first postion permission which is READ_EXTERNAL_STORAGE
// grantResult[1] means it will check for the Second postion permission which is CAMERA
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
return;
}
}
}
This Will Surely help you
1.open PhpMyAdmin.
2.on the left side under the PhpMyAdmin logo click on second icon(Empty Session Data).
3.that's it.
Technically, Python always uses pass by reference values. I am going to repeat my other answer to support my statement.
Python always uses pass-by-reference values. There isn't any exception. Any variable assignment means copying the reference value. No exception. Any variable is the name bound to the reference value. Always.
You can think about a reference value as the address of the target object. The address is automatically dereferenced when used. This way, working with the reference value, it seems you work directly with the target object. But there always is a reference in between, one step more to jump to the target.
Here is the example that proves that Python uses passing by reference:
If the argument was passed by value, the outer lst
could not be modified. The green are the target objects (the black is the value stored inside, the red is the object type), the yellow is the memory with the reference value inside -- drawn as the arrow. The blue solid arrow is the reference value that was passed to the function (via the dashed blue arrow path). The ugly dark yellow is the internal dictionary. (It actually could be drawn also as a green ellipse. The colour and the shape only says it is internal.)
You can use the id()
built-in function to learn what the reference value is (that is, the address of the target object).
In compiled languages, a variable is a memory space that is able to capture the value of the type. In Python, a variable is a name (captured internally as a string) bound to the reference variable that holds the reference value to the target object. The name of the variable is the key in the internal dictionary, the value part of that dictionary item stores the reference value to the target.
Reference values are hidden in Python. There isn't any explicit user type for storing the reference value. However, you can use a list element (or element in any other suitable container type) as the reference variable, because all containers do store the elements also as references to the target objects. In other words, elements are actually not contained inside the container -- only the references to elements are.
For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.
import { MatSelectModule } from '@angular/material';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CreateUserComponent ],
imports : [ReactiveFormsModule,
MatSelectModule,
MatAutocompleteModule,......
],
providers: [.........]
})
.compileComponents();
}));
Build from source and install, this is fixed in the latest release (10.3+):
mkdir -p /tmp/install/netifaces/
cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e"
tar xvzf netifaces-0.10.4.tar.gz
cd netifaces-0.10.4 && python setup.py install
You can directly use the Dimensions
module and calc your views sizes.
Actually, Dimensions
give to you the main window sizes.
import { Dimensions } from 'Dimensions';
Dimensions.get('window').height;
Dimensions.get('window').width;
Hope to help you!
Update: Today using native StyleSheet
with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...
Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components
You don't need to use a type assertion, instead just use the %v
format specifier with Sprintf
:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.
If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.
I hope this was useful to you.
The iPhone doesn't accept any message text, it will only take in the phone number. You can see this here https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/SMSLinks/SMSLinks.html#//apple_ref/doc/uid/TP40007899-CH7-SW1
Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.
Given "foo.csv" as follows:
FirstColumn,SecondColumn
asdf,1234
qwer,5678
Use DictReader like this:
import csv
with open('foo.csv') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
print(row['FirstColumn']) # Access by column header instead of column number
print(row['SecondColumn'])
The shortcuts I use in Visual Studio for multiline (aka box) select are Shift + Alt + up/down/left/right
To create this in Visual Studio Code you can add these keybindings to the keybindings.json file (menu File → Preferences → Keyboard shortcuts).
{ "key": "shift+alt+down", "command": "editor.action.insertCursorBelow",
"when": "editorTextFocus" },
{ "key": "shift+alt+up", "command": "editor.action.insertCursorAbove",
"when": "editorTextFocus" },
{ "key": "shift+alt+right", "command": "cursorRightSelect",
"when": "editorTextFocus" },
{ "key": "shift+alt+left", "command": "cursorLeftSelect",
"when": "editorTextFocus" }
You're probably better off comparing the fields individually, rather than concatenating the strings.
SELECT t1.*
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.MAKE = t2.MAKE
AND t1.MODEL = t2.MODEL
AND t1.[serial number] = t2.[serial number]
WHERE t2.MAKE IS NULL
For iOS 7 and above (Referring MKMapView.h) :
// Position the map such that the provided array of annotations are all visible to the fullest extent possible.
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
remark from – Abhishek Bedi
You just call:
[yourMapView showAnnotations:@[yourAnnotation] animated:YES];
In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="#" alt="" />
</div>
</div>
see closed issue: https://github.com/twbs/bootstrap/issues/20830
(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)
var btn = document.querySelector('#twofuns');_x000D_
btn.addEventListener('click',method1);_x000D_
btn.addEventListener('click',method2);_x000D_
function method2(){_x000D_
console.log("Method 2");_x000D_
}_x000D_
function method1(){_x000D_
console.log("Method 1");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Pramod Kharade-Javascript</title>_x000D_
</head>_x000D_
<body>_x000D_
<button id="twofuns">Click Me!</button>_x000D_
</body>_x000D_
</html>
_x000D_
You can achieve/call one event with one or more methods.
Standard approach:
from collections import defaultdict
words = "apple banana apple strawberry banana lemon"
words = words.split()
result = defaultdict(int)
for word in words:
result[word] += 1
print result
Groupby oneliner:
from itertools import groupby
words = "apple banana apple strawberry banana lemon"
words = words.split()
result = dict((key, len(list(group))) for key, group in groupby(sorted(words)))
print result
setLocationRelativeTo(null)
should be called after you either use setSize(x,y)
, or use pack()
.
It looks like you have a 64bit arch, fine -- but a 32bit version of the .NET runtime and/or a 32bit version of Windows.
And as such, the address space available to your process is still the same, it has not changed from your previous setup.
Upgrade to both a 64bit OS and a 64bit .NET version ;)
You can make a view with a different dtype, and then copy in-place into the view:
import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x
print(y)
yields
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
To show the conversion was in-place, note that copying from x
to y
altered x
:
print(x)
prints
array([ 0, 1065353216, 1073741824, 1077936128, 1082130432,
1084227584, 1086324736, 1088421888, 1090519040, 1091567616])
This is is the same as a weighted average problem where all the weights are the same, and there are two dimensions.
Find the average of all latitudes for your center latitude and the average of all longitudes for the center longitude.
Caveat Emptor: This is a close distance approximation and the error will become unruly when the deviations from the mean are more than a few miles due to the curvature of the Earth. Remember that latitudes and longitudes are degrees (not really a grid).
Don't forget to implement Serializable in every class your object will use like a list of objects. Else your app will crash.
Example:
public class City implements Serializable {
private List<House> house;
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}}
Then House needs to implements Serializable as so :
public class House implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
Then you can use:
Bundle bundle = new Bundle();
bundle.putSerializable("city", city);
intent.putExtras(bundle);
And retreive it with:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
City city = (City)bundle.getSerializable("city");
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
Here is a working version using v3
of docker-compose.yml
. The key is the volumes directive:
mysql:
image: mysql:5.6
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: theusername
MYSQL_PASSWORD: thepw
MYSQL_DATABASE: mydb
volumes:
- ./data:/docker-entrypoint-initdb.d
In the directory that I have my docker-compose.yml
I have a data
dir that contains .sql
dump files. This is nice because you can have a .sql
dump file per table.
I simply run docker-compose up
and I'm good to go. Data automatically persists between stops. If you want remove the data and "suck in" new .sql
files run docker-compose down
then docker-compose up
.
If anyone knows how to get the mysql
docker to re-process files in /docker-entrypoint-initdb.d
without removing the volume, please leave a comment and I will update this answer.
Well, after long research, i found a workaround that does what i need: http://jsfiddle.net/CqB3d/25/
CSS:
body{
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
height: 100%;
max-height: 100%;
}
#caixa{
width: 800px;
margin-left: auto;
margin-right: auto;
}
#framecontentTop, #framecontentBottom{
position: absolute;
top: 0;
width: 800px;
height: 100px; /*Height of top frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#framecontentBottom{
top: auto;
bottom: 0;
height: 110px; /*Height of bottom frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#maincontent{
position: fixed;
top: 100px; /*Set top value to HeightOfTopFrameDiv*/
margin-left:auto;
margin-right: auto;
bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/
overflow: auto;
background: #fff;
width: 800px;
}
.innertube{
margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/
}
* html body{ /*IE6 hack*/
padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/
}
* html #maincontent{ /*IE6 hack*/
height: 100%;
width: 800px;
}
HTML:
<div id="framecontentBottom">
<div class="innertube">
<h3>Sample text here</h3>
</div>
</div>
<div id="maincontent">
<div class="innertube">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text...
</div>
</div>
might not work with the horizontal thingy yet, but, it's a work in progress!
I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.
Hope this might help whoever finds the question later!
EDIT: This is the final answer.
With java 1.8 stream can be used ,
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> list = Arrays.asList("Bill","Bob","Steve").
String str = list.stream().collect(Collectors.joining(" and "));
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
The assertNotNull()
method means "a passed parameter must not be null
": if it is null then the test case fails.
The assertNull()
method means "a passed parameter must be null
": if it is not null then the test case fails.
String str1 = null;
String str2 = "hello";
// Success.
assertNotNull(str2);
// Fail.
assertNotNull(str1);
// Success.
assertNull(str1);
// Fail.
assertNull(str2);
C#:
ChromeOptions options = new ChromeOptions();
options.AddArgument("C:/Users/username/Documents/Visual Studio 2012/Projects/Interaris.Test/Interaris.Tes/bin/Debug/chromedriver.exe");
ChromeDriver chrome = new ChromeDriver(options);
Worked for me.
In Android Studio, you can go through following steps to add an image to drawable folder:
Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using
$files.length # evaluates to array length
And before you say "well obviously", consider this. If you had an array of objects with a capacity property then
$objarr.capacity
would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.
(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)
I came across this post and none of the solutions worked, so here is my solution that does work
Problems with other solutions thus far:
1) No explicit solution as to how the duration is modified
2) No solution for the out of order directory iteration, which is essential for GIFs
3) No explanation of how to install imageio for python 3
install imageio like this: python3 -m pip install imageio
Note: you'll want to make sure your frames have some sort of index in the filename so they can be sorted, otherwise you'll have no way of knowing where the GIF starts or ends
import imageio
import os
path = '/Users/myusername/Desktop/Pics/' # on Mac: right click on a folder, hold down option, and click "copy as pathname"
image_folder = os.fsencode(path)
filenames = []
for file in os.listdir(image_folder):
filename = os.fsdecode(file)
if filename.endswith( ('.jpeg', '.png', '.gif') ):
filenames.append(filename)
filenames.sort() # this iteration technique has no built in order, so sort the frames
images = list(map(lambda filename: imageio.imread(filename), filenames))
imageio.mimsave(os.path.join('movie.gif'), images, duration = 0.04) # modify duration as needed
It's not too hard.
Things to take into consideration:
Animated gifs:
If you are looking for animated gifs you can generate them:
AjaxLoad - Ajax Loading gif generator
Another way of doing it:
Another way that I have found that works quite well is the async dialog control that I found on the code project
The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:
=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
You can clear the whole form using onclick function.Here is the code for it.
<button type="reset" value="reset" type="reset" class="btnreset" onclick="window.location.reload()">Reset</button>
window.location.reload() function will refresh your page and all data will clear.
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
Angus Croll recently wrote an interesting blog post about this -
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
He goes through the pros and cons of the various methods then defines a new method 'toType' -
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
Just change from ProgressDialog
to ProgressBar
in a layout:
res/layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
//Your content here
</LinearLayout>
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"
android:indeterminateDrawable="@drawable/progress" >
</ProgressBar>
</RelativeLayout>
src/yourPackage/YourActivity.java
public class YourActivity extends Activity{
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
bar = (ProgressBar) this.findViewById(R.id.progressBar);
new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
@Override
protected void onPreExecute(){
bar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
//my stuff is here
}
@Override
protected void onPostExecute(Void result) {
bar.setVisibility(View.GONE);
}
}
}
drawable/progress.xml This is a custom ProgressBar
that i use to change the default colors.
<?xml version="1.0" encoding="utf-8"?>
<!--
Duration = 1 means that one rotation will be done in 1 second. leave it.
If you want to speed up the rotation, increase duration value.
in example 1080 shows three times faster revolution.
make the value multiply of 360, or the ring animates clunky
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1"
android:toDegrees="360" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="8"
android:useLevel="false" >
<size
android:height="48dip"
android:width="48dip" />
<gradient
android:centerColor="@color/color_preloader_center"
android:centerY="0.50"
android:endColor="@color/color_preloader_end"
android:startColor="@color/color_preloader_start"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
URL url = getClass().getClassLoader().getResource("someresource.xxx");
That should do it.
I adapted and modified the code from this tutorial to write a function that does a deep comparison of two JS objects.
const isEqual = function(obj1, obj2) {
const obj1Keys = Object.keys(obj1);
const obj2Keys = Object.keys(obj2);
if(obj1Keys.length !== obj2Keys.length) {
return false;
}
for (let objKey of obj1Keys) {
if (obj1[objKey] !== obj2[objKey]) {
if(typeof obj1[objKey] == "object" && typeof obj2[objKey] == "object") {
if(!isEqual(obj1[objKey], obj2[objKey])) {
return false;
}
}
else {
return false;
}
}
}
return true;
};
The function compares the respective values of the same keys for the two objects. Further, if the two values are objects, it uses recursion to execute deep comparison on them as well.
Hope this helps.
Style property can be used For HTML5 if you want to remove the boder of your frame or anything you can use the style property. as given below
Code goes here
<iframe src="demo.htm" style="border:none;"></iframe>
Jakarta Commons Math has exactly that.
I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.
Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Actually, the best solution is using JSON:
JSON.parse(text[, reviver]);
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3) Passing a function to JSON
var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();
You can iterate through the array or you can convert it to a String
and use indexOf
.
if (new String(charArray).indexOf('q') < 0) {
break;
}
Creating a new String
is a bit wasteful, but it's probably the tersest code. You can also write a method to imitate the effect without incurring the overhead.
There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.
In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.
You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; }
is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
You need to set the $JAVA_HOME variable
In my case while setting up Maven, I had to set it up to where JDK is installed.
First find out where JAVA is installed:
$ whereis java
java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz
Now dig deeper-
$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 46 Aug 25 2018 /etc/alternatives/java -> /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java Dig deeper:
$ ls -l /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
-rwxr-xr-x 1 root root 6464 Mar 14 18:28 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
As it is not being referenced to any other directory, we'll use this.
Open /etc/environment using nano
$ sudo nano /etc/environment
Append the following lines
JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
export JAVA_HOME
Reload PATH using
$. /etc/environment
Now,
$ echo $JAVA_HOME
Here is your output:
/usr/lib/jvm/java-1.8.0-openjdk-amd64
Sources I referred to:
If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.
You do not need the -p
option in order to expose ports from container to host. By default, all port are exposed. The -p
option allows you to expose a port from the container to the outside of the host.
So, my guess is that you do not need -p
at all and it should be working fine :)
CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
The leading ', '
and trailing ','
are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).
That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.
In addition: don't use 'single quotes'
as identifier delimiters; this syntax is deprecated. Use [square brackets]
(preferred) or "double quotes"
if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx
EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE
syntax variant or by using something like IN()
):
CASE
WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
If you have more values, it might be worthwhile to use a split function, e.g.
USE tempdb;
GO
CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List,',', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO
INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');
SELECT t.ID
FROM dbo.[Table] AS t
INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
GROUP BY t.ID;
GO
Results:
ID
----
1
2
4
One simple rewrite of the command in the question is:
grep "word1" logs | grep "word2"
The first grep
finds lines with 'word1' from the file 'logs' and then feeds those into the second grep
which looks for lines containing 'word2'.
However, it isn't necessary to use two commands like that. You could use extended grep
(grep -E
or egrep
):
grep -E 'word1.*word2|word2.*word1' logs
If you know that 'word1' will precede 'word2' on the line, you don't even need the alternatives and regular grep
would do:
grep 'word1.*word2' logs
The 'one command' variants have the advantage that there is only one process running, and so the lines containing 'word1' do not have to be passed via a pipe to the second process. How much this matters depends on how big the data file is and how many lines match 'word1'. If the file is small, performance isn't likely to be an issue and running two commands is fine. If the file is big but only a few lines contain 'word1', there isn't going to be much data passed on the pipe and using two command is fine. However, if the file is huge and 'word1' occurs frequently, then you may be passing significant data down the pipe where a single command avoids that overhead. Against that, the regex is more complex; you might need to benchmark it to find out what's best — but only if performance really matters. If you run two commands, you should aim to select the less frequently occurring word in the first grep
to minimize the amount of data processed by the second.
The initial script is:
grep -c "word1" | grep -r "word2" logs
This is an odd command sequence. The first grep
is going to count the number of occurrences of 'word1' on its standard input, and print that number on its standard output. Until you indicate EOF (e.g. by typing Control-D), it will sit there, waiting for you to type something. The second grep
does a recursive search for 'word2' in the files underneath directory logs
(or, if it is a file, in the file logs
). Or, in my case, it will fail since there's neither a file nor a directory called logs
where I'm running the pipeline. Note that the second grep
doesn't read its standard input at all, so the pipe is superfluous.
With Bash, the parent shell waits until all the processes in the pipeline have exited, so it sits around waiting for the grep -c
to finish, which it won't do until you indicate EOF. Hence, your code seems to get stuck. With Heirloom Shell, the second grep
completes and exits, and the shell prompts again. Now you have two processes running, the first grep
and the shell, and they are both trying to read from the keyboard, and it is not determinate which one gets any given line of input (or any given EOF indication).
Note that even if you typed data as input to the first grep
, you would only get any lines that contain 'word2' shown on the output.
Footnote:
At one time, the answer used:
grep -E 'word1.*word2|word2.*word1' "$@"
grep 'word1.*word2' "$@"
This triggered the comments below.
For Bootstrap version 3.1.1 and above, the best class for centering the content is the .center-block
helper class.
Check This module keyboard with many features.Install it, perhaps with this command:
pip3 install keyboard
Then Use this Code:
import keyboard
keyboard.write('A',delay=0)
If you Want to write 'A' multiple times, Then simply use a loop.
Note:
The key 'A' will be pressed for the whole windows.Means the script is running and you went to browser, the script will start writing there.
I have done for
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
A couple of distinctions that weren't touched on here:
Compare:
exec('ls', $out);
var_dump($out);
// Look an array
$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it
Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you'll need to post-process the input into some other form, so in that case use shell_exec.
It's also worth pointing out that shell_exec is an alias for the backtic operator, for those used to *nix.
$out = `ls`;
var_dump($out);
exec also supports an additional parameter that will provide the return code from the executed command:
exec('ls', $out, $status);
if (0 === $status) {
var_dump($out);
} else {
echo "Command failed with status: $status";
}
As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec.
Using -XX:+UseParNewGC along with -XX:+UseConcMarkSweepGC, will cause higher pause time for Minor GCs, when compared to -XX:+UseParallelGC.
This is because, promotion of objects from Young to Old Generation will require running a Best-Fit algorithm (due to old generation fragmentation) to find an address for this object.
Running such an algorithm is not required when using -XX:+UseParallelGC, as +UseParallelGC can be configured only with MarkandCompact Collector, in which case there is no fragmentation.
For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant
. There's a tutorial, or you could just dive straight in:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
PyEnchant
comes with a few dictionaries (en_GB, en_US, de_DE, fr_FR), but can use any of the OpenOffice ones if you want more languages.
There appears to be a pluralisation library called inflect
, but I've no idea whether it's any good.
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).
I would use sed
:
sed 's/, /,/' input.txt
This will remove on leading space after the ,
.
Output:
Name,Order
Trim,working
cat,cat1
More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,
:
sed 's/,[ \t]\?/,/g' input.txt
It will also work with more than two columns because of the global modifier /g
@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:
sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt
*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *
IMO sed
is the optimal tool for this job. However, here comes a solution with awk
because you've asked for that:
awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
Another simple solution that comes in mind to remove all whitespaces is tr -d
:
cat input.txt | tr -d ' '
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)
Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.
The easiest way is to draw the primitives as GL_LINE_STRIP
.
glBegin(GL_LINE_STRIP);
/* Draw vertices here */
glEnd();
Apple cares about security and as you know it is not possible to install any application on a real iOS device. Apple has several legal ways to do it:
Development Provisioning Profile
allows you to do itDistribution Provisioning Profile
[About] and Apple after review reassign it by they own keyDevelopment Provisioning Profile
is stored on device and contains:
Xcode
by default take cares about
img {
filter: blur(var(--blur));
}
But for a better check:
if(str === null || str === '')
{
//enter code here
}
Just learning this myself. I will answer the second question:
Instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:
var path = require("path");
var express = require("express");
var DIST_DIR = path.join(__dirname, "build");
var PORT = 3000;
var app = express();
//Serving the files on the dist folder
app.use(express.static(DIST_DIR));
//Send index.html when the user access the web
app.get("*", function (req, res) {
res.sendFile(path.join(DIST_DIR, "index.html"));
});
app.listen(PORT);
Then, in the package.json, add a script:
"start": "node server.js"
Finally, run the app: npm run start
to start the server
A detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (the example code is not compatible with the latest packages, but it will work with small tweaks)
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent
situation than a wrap_content
situation). These constraints are packaged up into the MeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:
layout_width
or layout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_width
or layout_height
value was set to match_parent
or wrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.layout_width
or layout_height
value was set to wrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.The contract that exists with onMeasure()
is that setMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View
, which is why it is safe to call super
instead if that fits your use case.
Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!
Generally, if you are overriding View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
Hope that Helps.
grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX
and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
I recommend using a autocomplete environment(pyscripter or scipy for example). If you lookup example code, make sure they use the same version of Python(if they don't make sure you change the code).
You can use following code:
sendButton.enabled = YES;
sendButton.alpha = 1.0;
or
sendButton.enabled = NO;
sendButton.alpha = 0.5;
There are many ways to compare files from two different branches:
Option 1: If you want to compare the file from n specific branch to another specific branch:
git diff branch1name branch2name path/to/file
Example:
git diff mybranch/myfile.cs mysecondbranch/myfile.cs
In this example you are comparing the file in “mybranch” branch to the file in the “mysecondbranch” branch.
Option 2: Simple way:
git diff branch1:file branch2:file
Example:
git diff mybranch:myfile.cs mysecondbranch:myfile.cs
This example is similar to the option 1.
Option 3: If you want to compare your current working directory to some branch:
git diff ..someBranch path/to/file
Example:
git diff ..master myfile.cs
In this example you are comparing the file from your actual branch to the file in the master branch.
Since a for-loop is used to iterate over an array, or similar iterable data structure, we can use the length of the array as shown,
awk -v header="FirstName,LastName,DOB" '
BEGIN {
FS = ",";
print("[");
columns = split(header, column_names, ",");
}
{ print(" {");
for (i = 1; i < columns; i++) {
printf(" \"%s\":\"%s\",\n", column_names[i], $(i));
}
printf(" \"%s\":\"%s\"\n", column_names[i], $(i));
print(" }");
}
END { print("]"); } ' datafile.txt
With datafile.txt containing,
Angela,Baker,2010-05-23
Betty,Crockett,1990-12-07
David,Done,2003-10-31
The module needs to be placed in a folder with the same name as the module. In your case:
$home/WindowsPowerShell/Modules/XMLHelpers/
The full path would be:
$home/WindowsPowerShell/Modules/XMLHelpers/XMLHelpers.psm1
You would then be able to do:
import-module XMLHelpers
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
Just for fun I thought I'd throw a forEach(f())
solution in too.
var a=[];
"14 2".split(" ").forEach(function(e){a.push(parseInt(e,10))});
// a = [14,2]
Found the problem, need to use function(err,obj)
instead:
Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
Another interesting use of references is to supply a default argument of a user-defined type:
class UDT
{
public:
UDT() : val_d(33) {};
UDT(int val) : val_d(val) {};
virtual ~UDT() {};
private:
int val_d;
};
class UDT_Derived : public UDT
{
public:
UDT_Derived() : UDT() {};
virtual ~UDT_Derived() {};
};
class Behavior
{
public:
Behavior(
const UDT &udt = UDT()
) {};
};
int main()
{
Behavior b; // take default
UDT u(88);
Behavior c(u);
UDT_Derived ud;
Behavior d(ud);
return 1;
}
The default flavor uses the 'bind const reference to a temporary' aspect of references.
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
iris_df = pd.DataFrame(X, columns = iris['feature_names'])
iris_df.head()
Maybe something like:
$(".subclass", this);
origin is a name for remote git url. There can be many more remotes example below.
bangalore => bangalore.example.com:project.git boston => boston.example.com:project.git
as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.
It is possible that remote bangalore has advanced since you have done "fetch" or "pull"
Few points
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
is wrong
it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
since y
holds pointer to struct Vector
.
1st malloc()
only allocates memory enough to hold Vector structure (which is pointer to double + int)
2nd malloc()
actually allocate memory to hold 10 double.
using the Integer data type with values 0 and 1 is the fastest.
The Union command is what you need. If that doesn't work, you may need to refine what environment you are in.
There is no builtin function, but you can easily achieve it by calling the functions min()
and max()
appropriately.
// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);
I generally subscribe to the following convention:
Here is the example from w3chools that was mentioned.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
I recommend not using WebClient.DownloadString
. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM (
) incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!
Instead, this slight variation will work correctly with BOMs:
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
Android hasn't provided a native method. Nor the AppCompat.
Try this library: https://github.com/rengwuxian/MaterialEditText
This might be what you want.
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
Found various approaches to refresh the application in selenium :-
1.driver.navigate().refresh();
2.driver.get(driver.getCurrentUrl());
3.driver.navigate().to(driver.getCurrentUrl());
4.driver.findElement(By.id("Contact-us")).sendKeys(Keys.F5);
5.driver.executeScript("history.go(0)");
For live code, please refer the link http://www.ufthelp.com/2014/11/Methods-Browser-Refresh-Selenium.html
I hate adding to such a huge topic and so much later, but I've think I have a solution that work in VS2015 at the very least.
I was on a hunt to find a reason for the sys error, and the only solution that worked for me was to add EnableCdn="true"
in a ScriptManager
like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true" />
See the MSDN for more information.
Why do we need to do this?
When working on a asp.net web application, you have to enable CDN so that Microsoft can download the Sys.
library.
There was probably a script in your page that was using the Sys
function. Setting EnableCdn="true"
would ensure that the Sys
library is downloaded before it is used.
What's CDN?
A quote from https://www.sitepoint.com/7-reasons-to-use-a-cdn/
Most CDNs are used to host static resources such as images, videos, audio clips, CSS files and JavaScript. You’ll find common JavaScript libraries, HTML5 shims, CSS resets, fonts and other assets available on a variety of public and private CDN systems.
Both Google and Microsoft have CDNs. All you have to do is add a reference. Usually CDNs are added via a script resource:
<script src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js" type="text/javascript"></script>
Once you set EnableCdn="true"
and Microsoft will add it's little CDN reference (like the one above) in the page which downloads the Sys
library.
I hope that helps anybody that ran into the same issue.
In my case, using Mockito 2.0, I had to change all the any()
parameters to nullable()
in order to stub the real call.
When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".
Add to your parent layout where did you put your EditText
this android:focusableInTouchMode="true"
Visual Studio 2015:
Tools > Options > Settings > Environment > Keyboard
Defaults:
Edit.CollapsetoDefinitions: CTRL + M + O
Edit.CollapseCurrentRegion: CTRL + M +CTRL + S
Edit.ExpandAllOutlining: CTRL + M + CTRL + X
Edit.ExpandCurrentRegion: CTRL + M + CTRL + E
I like to set and use IntelliJ's shortcuts:
Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-
Edit.CollapseCurrentRegion: CTRL + NUM-
Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+
Edit.ExpandCurrentRegion: CTRL + NUM+
downgrade to 6.2 helped me.
.NET Framework version 4.6.1
Project in old format(non .NET Standard)
Visual Studio should be open with Admin rights for initial migration.
I guess EF with version above 6.2 require latest .NET Framework.
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
Use the \
character to escape a character that has special meaning inside a regular expression.
To automate it, you could use this:
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape
Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.
Check whether nano was actually built with UTF-8 support, using nano --version
. Here it is on Cygwin:
nano --version
GNU nano version 2.2.5 (compiled 21:04:20, Nov 3 2010)
(C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
2008, 2009 Free Software Foundation, Inc.
Email: [email protected] Web: http://www.nano-editor.org/
Compiled options: --enable-color --enable-extra --enable-multibuffer
--enable-nanorc --enable-utf8
Note the last bit.
To be honest - there aren't any free alternatives to MS Access. At least if you mean database development tool (forms, reports, queries, VBA support etc.). If you think about MS Access as a database engine (you mean MS Jet or ACE in fact) then yes - you have a lot of possibilities. There are a lot of free database engines - the most popular are MySQL and PostgreSQL. I can recommend both - it depends what you want to do.
For writing database frontends C++ is one of the worst choices. You should consider MS Visual C#, MS Visual Basic .NET or... Even Java/Swing (if we are talking about desktop application). If you think about the web-enabled frontend - consider PHP (with MySQL or PostgreSQL on the backend) or ASP.NET (with MSSQL Server at the backend).
I strongly recommend you not to use C++ for such job. This language is very efficient and flexible, but advanced database frontend development with C++ is not the best idea. C++ is great in system programming, games development, maths and physics simulations, everywhere where efficiency is the key - like real-time applications etc. Frontends don't have to be daemons of speed - they should look nice and have advanced end-user features (like sorting, coloring etc.). If you are looking for free tools - maybe C# Express or Visual Basic.NET Express 2008 would be the proper choice? Or maybe Java/Swing (check the NetBeans IDE)? Maybe SharpDevelop? But not C++... Leave C++ for the things it suits the best.
Right click on Git Bash shortcut
and then go to properties
.
In properties
inside start in
option add the location of the directory you want to start Git Bash
in and apply
the changes.
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #