Screen pixel density and resolution vary depending on the platform. Device-independent pixels and scalable pixels are units that provide a flexible way to accommodate a design across platforms.
The number of pixels that fit into an inch is referred to as pixel density. High-density screens have more pixels per inch than low-density ones....
The number of pixels that fit into an inch is referred to as pixel density. High-density screens have more pixels per inch than low-density ones. As a result, UI elements of the same pixel dimensions appear larger on low-density screens, and smaller on high-density screens.
To calculate screen density, you can use this equation:
Screen density = Screen width (or height) in pixels / Screen width (or height) in inches
Screen pixel density and resolution vary depending on the platform. Device-independent pixels and scalable pixels are units that provide a flexible way to accommodate a design across platforms.
Calculating pixel density The number of pixels that fit into an inch is referred to as pixel density. High-density screens have more pixels per inch than low-density ones....
Density independence refers to the uniform display of UI elements on screens with different densities.
Density-independent pixels, written as dp (pronounced “dips”), are flexible units that scale to have uniform dimensions on any screen. Material UIs use density-independent pixels to display elements consistently on screens with different densities.
Read full text https://material.io/design/layout/pixel-density.html
If you just want to change the size font dynamically then you can:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.tutorial_cross_marginTop))
As @achie's answer, you can get the dp from dimens.xml like this:
val dpValue = (resources.getDimension(R.dimen.tutorial_cross_marginTop)/ resources.displayMetrics.density).toInt()
or get sp like this
val spValue = (resources.getDimension(R.dimen.font_size)/ resources.displayMetrics.scaledDensity).toInt()
About Resources.java #{getDimension}
/**
* Retrieve a dimensional for a particular resource ID. Unit
* conversions are based on the current {@link DisplayMetrics} associated
* with the resources.
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
*
* @return Resource dimension value multiplied by the appropriate
* metric.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @see #getDimensionPixelOffset
* @see #getDimensionPixelSize
*/
Resource dimension value multiplied by the appropriate
check your casing, the name is typically stored in upper case
SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;
Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...
Converting anything to a string should either 1) allocate the resultant string or 2) pass in a char *
destination and size. Sample code below:
Both work for all int
including INT_MIN
. They provide a consistent output unlike snprintf()
which depends on the current locale.
Method 1: Returns NULL
on out-of-memory.
#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)
char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf - 1];
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}
Method 2: It returns NULL
if the buffer was too small.
static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}
char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}
[Edit] as request by @Alter Mann
(CHAR_BIT*sizeof(int_type)-1)*10/33+3
is at least the maximum number of char
needed to encode the some signed integer type as a string consisting of an optional negative sign, digits, and a null character..
The number of non-sign bits in a signed integer is no more than CHAR_BIT*sizeof(int_type)-1
. A base-10 representation of a n
-bit binary number takes up to n*log10(2) + 1
digits. 10/33
is slightly more than log10(2)
. +1 for the sign char
and +1 for the null character. Other fractions could be used like 28/93.
Method 3: If one wants to live on the edge and buffer overflow is not a concern, a simple C99 or later solution follows which handles all int
.
#include <limits.h>
#include <stdio.h>
static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}
char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}
int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}
Sample output
0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648
After I installed Visual Studio 2013 Update 2, Visual Studio notified me about a Windows Phone emulator update, which I installed (it was really a new component, not an update). It turned out this enabled Hyper-V, which broke HAXM.
The solution was to uninstall the emulator from Programs and Features and to turn off Hyper-V from Windows Features (search for "Windows Features" and click "Turn Windows features on or off").
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
As I can't comment, I'll expand on Alex's fantastic answer.
If you want the Sublime-like experience with wrapping open up the Keymap Extensions (Preferences > Keymap Extensions [Cmd+K Cmd+M]) and add the following object:
{
"key": "alt+w",
"command": "editor.emmet.action.wrapIndividualLinesWithAbbreviation",
"when": "editorHasSelection && editorTextFocus"
}
Which will bind the Emmet wrap command to Alt+W when text is selected
(Sorry for OSX only instructions)
This one shows how to print only selected element on the page with dpi/resolution
adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Hope this helps!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
You Could Try This Fibonacci Solution Here
var a = 0;
console.log(a);
var b = 1;
console.log(b);
var c;
for (i = 0; i < 3; i++) {
c = a + b;
console.log(c);
a = b + c;
console.log(a);
b = c + a;
console.log(b);
}
An efficient way to loop over an Array is the built-in array method .map()
For a 1-dimensional array it would look like this:
function HandleOneElement( Cuby ) {
Cuby.dimension
Cuby.position_x
...
}
cubes.map(HandleOneElement) ; // the map function will pass each element
for 2-dimensional array:
cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )
for an n-dimensional array of any form:
Function.prototype.ArrayFunction = function(param) {
if (param instanceof Array) {
return param.map( Function.prototype.ArrayFunction, this ) ;
}
else return (this)(param) ;
}
HandleOneElement.ArrayFunction(cubes) ;
I found this question while trying determine how to use/encode/decode a string whose encoding I wasn't sure of (and how to escape/convert special characters in that string).
My first step should have been to check the type of the string- I didn't realize there I could get good data about its formatting from type(s). This answer was very helpful and got to the real root of my issues.
If you're getting a rude and persistent
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 263: ordinal not in range(128)
particularly when you're ENCODING, make sure you're not trying to unicode() a string that already IS unicode- for some terrible reason, you get ascii codec errors. (See also the Python Kitchen recipe, and the Python docs tutorials for better understanding of how terrible this can be.)
Eventually I determined that what I wanted to do was this:
escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace'))
Also helpful in debugging was setting the default coding in my file to utf-8 (put this at the beginning of your python file):
# -*- coding: utf-8 -*-
That allows you to test special characters ('àéç') without having to use their unicode escapes (u'\xe0\xe9\xe7').
>>> specials='àéç'
>>> specials.decode('latin-1').encode('ascii','xmlcharrefreplace')
'àéç'
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
All credits are to Frank Tzanabetis. However this is the shortest direct example, that also survives in case of empty string or broken original JSON string:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
...
try
{
return JToken.Parse(jsonString).ToString(Formatting.Indented);
}
catch
{
return jsonString;
If you want a "const string" like your question says, I would really go for the version you stated in your question:
/* first version */
const char *HELLO2 = "Howdy";
Particularly, I would avoid:
/* second version */
const char HELLO2[] = "Howdy";
Reason: The problem with second version is that compiler will make a copy of the entire string "Howdy", PLUS that string is modifiable (so not really const).
On the other hand, first version is a const string accessible by const pointer HELLO2, and there is no way anybody can modify it.
Just another solution using underscore.js:
_.extend({}, obj1, obj2);
You'll need to open the workbook to refer to it.
Sub Setwbk()
Dim wbk As Workbook
Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
Master Benchmark Data Sheet.xlsx")
End Sub
* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:
Why do I have to "set" it?
Set
is how VBA assigns object variables. Since a Range
and a Workbook
/Worksheet
are objects, you must use Set
with these.
The difference is the amount of memory allocated to each integer, and how large a number they each can store.
While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print
, or otherwise send Unicode strings to stdout
, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use:
File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
This means the charset is cp850
.
You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850')
. Or you can look up cp850 online (e.g., at Wikipedia).
It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'
.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)
But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:
>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'
So, how do you print a string that won't print on your console?
You can replace every print
function with something like this:
>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?
… but that's going to get pretty tedious pretty fast.
The simple thing to do is to just set the error handler on sys.stdout
:
>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?
For printing to a file, things are pretty much the same, except that you don't have to set f.errors
after the fact, you can set it at construction time. Instead of this:
with open('path', 'w', encoding='cp850') as f:
Do this:
with open('path', 'w', encoding='cp850', errors='replace') as f:
… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
with open('path', 'w', encoding='utf-8') as f:
returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.
Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$
:
^\w+$
Explanation:
Use /[^\w]|_/g
if you don't want to match the underscore.
It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.
So "C:\\Users\\Rich"
is the same as @"C:\Users\Rich"
There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @""""
evaluates to "
.
You have to increase client_max_body_size in nginx.conf
file. This is the basic step. But if your backend laravel
then you have to do some changes in the php.ini
file as well. It depends on your backend. Below I mentioned file location and condition name.
sudo vim /etc/nginx/nginx.conf.
After open the file adds this into HTTP section.
client_max_body_size 100M;
You can do that using CSS's background
propieties. There are few ways to do it:
HTML:
<div id="div-with-bg"></div>
CSS:
#div-with-bg
{
background: color url('path') others;
}
HTML:
<div class="div-with-bg"></div>
CSS:
.div-with-bg
{
background: color url('path') others;
}
HTML:
<div style="background: color url('path')"></div>
Where:
background
CSS Property is a connection of all background-xxx propieties in that syntax:
background: background-color background-image background-repeat background-attachment background-position;
Source: w3schools
All markers in Google Android Maps Api v2 are clickable. You don't need to set any additional properties to your marker. What you need to do - is to register marker click callback to your googleMap and handle click within callback:
public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
implements OnMarkerClickListener
{
private Marker myMarker;
private void setUpMap()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
@Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(myMarker))
{
//handle click here
}
}
}
here is a good guide on google about marker customization
The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).
If you don't want to run sudo
then install ruby using homebrew
brew install ruby
export GEM_HOME="$HOME/.gem"
gem install rails
You may want to add export GEM_HOME="$HOME/.gem"
to your ~/.bash_profile
or .zshrc
if you're using zsh
Note: RubyGems keeps old versions of gems, so feel free to do some cleaning after updating:
gem cleanup
This one shows the user's uid as well as all the groups (with their gids) they belong to
id userid
In Node.js, you can set global variables via the "global" or "GLOBAL" object:
GLOBAL._ = require('underscore'); // But you "shouldn't" do this! (see note below)
or more usefully...
GLOBAL.window = GLOBAL; // Like in the browser
From the Node.js source, you can see that these are aliased to each other:
node-v0.6.6/src/node.js:
28: global = this;
128: global.GLOBAL = global;
In the code above, "this" is the global context. With the CommonJS module system (which Node.js uses), the "this" object inside of a module (i.e., "your code") is not the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.
console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);
/* Outputs ...
THIS:
{}
GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
DataView: [Function: DataView],
global: [Circular],
process:
{ EventEmitter: [Function: EventEmitter],
title: 'node',
assert: [Function],
version: 'v0.6.5',
_tickCallback: [Function],
moduleLoadList:
[ 'Binding evals',
'Binding natives',
'NativeModule events',
'NativeModule buffer',
'Binding buffer',
'NativeModule assert',
'NativeModule util',
'NativeModule path',
'NativeModule module',
'NativeModule fs',
'Binding fs',
'Binding constants',
'NativeModule stream',
'NativeModule console',
'Binding tty_wrap',
'NativeModule tty',
'NativeModule net',
'NativeModule timers',
'Binding timer_wrap',
'NativeModule _linklist' ],
versions:
{ node: '0.6.5',
v8: '3.6.6.11',
ares: '1.7.5-DEV',
uv: '0.6',
openssl: '0.9.8n' },
nextTick: [Function],
stdout: [Getter],
arch: 'x64',
stderr: [Getter],
platform: 'darwin',
argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
stdin: [Getter],
env:
{ TERM_PROGRAM: 'iTerm.app',
'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
TERM: 'xterm',
SHELL: '/bin/bash',
TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
USER: 'ddopson',
COMMAND_MODE: 'unix2003',
SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
__CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
PWD: '/workspace/zd/zgap/darwin-js',
LANG: 'en_US.UTF-8',
ITERM_PROFILE: 'Default',
SHLVL: '1',
COLORFGBG: '7;0',
HOME: '/Users/ddopson',
ITERM_SESSION_ID: 'w0t0p0',
LOGNAME: 'ddopson',
DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
OLDPWD: '/workspace/zd/zgap/darwin-js/external',
_: './index.js' },
openStdin: [Function],
exit: [Function],
pid: 10321,
features:
{ debug: false,
uv: true,
ipv6: true,
tls_npn: false,
tls_sni: true,
tls: true },
kill: [Function],
execPath: '/usr/local/bin/node',
addListener: [Function],
_needTickCallback: [Function],
on: [Function],
removeListener: [Function],
reallyExit: [Function],
chdir: [Function],
debug: [Function],
error: [Function],
cwd: [Function],
watchFile: [Function],
umask: [Function],
getuid: [Function],
unwatchFile: [Function],
mixin: [Function],
setuid: [Function],
setgid: [Function],
createChildProcess: [Function],
getgid: [Function],
inherits: [Function],
_kill: [Function],
_byteLength: [Function],
mainModule:
{ id: '.',
exports: {},
parent: null,
filename: '/workspace/zd/zgap/darwin-js/index.js',
loaded: false,
exited: false,
children: [],
paths: [Object] },
_debugProcess: [Function],
dlopen: [Function],
uptime: [Function],
memoryUsage: [Function],
uvCounters: [Function],
binding: [Function] },
GLOBAL: [Circular],
root: [Circular],
Buffer:
{ [Function: Buffer]
poolSize: 8192,
isBuffer: [Function: isBuffer],
byteLength: [Function],
_charsWritten: 8 },
setTimeout: [Function],
setInterval: [Function],
clearTimeout: [Function],
clearInterval: [Function],
console: [Getter],
window: [Circular],
navigator: {} }
*/
** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');
. Yes, you do that in every single file that uses Underscore.js, just like how in Java you do import com.foo.bar;
. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. It is mildly annoying, but a good thing. .... That's the preaching.
There is an exception to every rule. I have had precisely exactly one instance where I needed to set "GLOBAL._". I was creating a system for defining "configuration" files which were basically JSON, but were "written in JavaScript" to allow a bit more flexibility. Such configuration files had no 'require' statements, but I wanted them to have access to Underscore.js (the entire system was predicated on Underscore.js and Underscore.js templates), so before evaluating the "configuration", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "I get tired of typing 'require', so I want to break with the convention".
I know there is already an answer to this but I just found a better solution using the variableWidth parameter, just set it to true in the settings of each breakpoint, like this:
$('#featured-articles').slick({
arrows: true,
autoplay: true,
autoplaySpeed: 3000,
dots: true,
draggable: false,
fade: true,
infinite: false,
responsive: [
{
breakpoint: 620,
settings: {
arrows: true,
variableWidth: true
}
},
{
breakpoint: 345,
settings: {
arrows: true,
variableWidth: true
}
}
]
});
Instead of using pull-right
class, it is better to use text-right
class in the column, because pull-right
creates problems sometimes while resizing the page.
You can wrap them in a div and give the div a set width (the width of the widest image + margin maybe?) and then float the divs. Then, set the images to the center of their containing divs. Your margins between images won't be consistent for the differently sized images but it'll lay out much more nicely on the page.
.btn{
font-size: 20px;
color:black;
}
And also if the input box/button has to remain disable, then simply
<button disabled>
or <input disabled>
works.
You can import the colorlog module and use its ColoredFormatter
for colorizing log messages.
Boilerplate for main module:
import logging
import os
import sys
try:
import colorlog
except ImportError:
pass
def setup_logging():
root = logging.getLogger()
root.setLevel(logging.DEBUG)
format = '%(asctime)s - %(levelname)-8s - %(message)s'
date_format = '%Y-%m-%d %H:%M:%S'
if 'colorlog' in sys.modules and os.isatty(2):
cformat = '%(log_color)s' + format
f = colorlog.ColoredFormatter(cformat, date_format,
log_colors = { 'DEBUG' : 'reset', 'INFO' : 'reset',
'WARNING' : 'bold_yellow', 'ERROR': 'bold_red',
'CRITICAL': 'bold_red' })
else:
f = logging.Formatter(format, date_format)
ch = logging.StreamHandler()
ch.setFormatter(f)
root.addHandler(ch)
setup_logging()
log = logging.getLogger(__name__)
The code only enables colors in log messages, if the colorlog module is installed and if the output actually goes to a terminal. This avoids escape sequences being written to a file when the log output is redirected.
Also, a custom color scheme is setup that is better suited for terminals with dark background.
Some example logging calls:
log.debug ('Hello Debug')
log.info ('Hello Info')
log.warn ('Hello Warn')
log.error ('Hello Error')
log.critical('Hello Critical')
Output:
If you want to get the actual script directory (irrespective of whether you are invoking the script using a symlink or directly), try:
BASEDIR=$(dirname $(realpath "$0"))
echo "$BASEDIR"
This works on both linux and macOS. I couldn't see anyone here mention about realpath
. Not sure whether there are any drawbacks in this approach.
on macOS, you need to install coreutils
to use realpath
. Eg: brew install coreutils
.
Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.
First of all you should stop using mysql_*. MySQL supports multiple inserting like
INSERT INTO example
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You just have to build one string in your foreach loop which looks like that
$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";
and then insert it after the loop
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;
Another way would be Prepared Statements, which are even more suited for your situation.
I used:
sudo yum install mod24_ssl
and it worked in my Amazon Linux AMI.
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:
error_reporting(E_ERROR);
Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.
So you should first set it as verbose as possible with:
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
UPDATE: how to log errors instead of displaying them
As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.
A possible implementation is via the .htaccess file, useful if you don't have access to the php.ini file (source).
# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
# Enable PHP error logging
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Prevent access to PHP error log
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
This answer is based on the question and title of this book: http://www.packtpub.com/angularjs-web-application-development/book
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
I faced the same exception while trying to test my web-services deployed to WSO2 ESB.
WSO2 generated both wsdl and wsdl2. I tried to pass a wsdl2 URL and got the above exception. Quick googling showed me, that one of differences between wsdl1.1 and wsdl2.0 is replacing 'definitions' element with 'description'. Also, I found out, that SoapUI does not support wsdl2.
Therefore, for me the solution was to use wsdl1 url instead of wsdl2.
If you do a
sudo yum list | grep python3
you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:
sudo yum install python34 python34-pip
In case anyone wants the answer of Dirk Vollmar in a C# switch statement:
case "doc": return "application/msword";
case "dot": return "application/msword";
case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
case "docm": return "application/vnd.ms-word.document.macroEnabled.12";
case "dotm": return "application/vnd.ms-word.template.macroEnabled.12";
case "xls": return "application/vnd.ms-excel";
case "xlt": return "application/vnd.ms-excel";
case "xla": return "application/vnd.ms-excel";
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
case "xlsm": return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "xltm": return "application/vnd.ms-excel.template.macroEnabled.12";
case "xlam": return "application/vnd.ms-excel.addin.macroEnabled.12";
case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
case "ppt": return "application/vnd.ms-powerpoint";
case "pot": return "application/vnd.ms-powerpoint";
case "pps": return "application/vnd.ms-powerpoint";
case "ppa": return "application/vnd.ms-powerpoint";
case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
case "ppam": return "application/vnd.ms-powerpoint.addin.macroEnabled.12";
case "pptm": return "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
case "potm": return "application/vnd.ms-powerpoint.template.macroEnabled.12";
case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
case "mdb": return "application/vnd.ms-access";
You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->group_start() //this will start grouping
->where('library.available_until >=', date("Y-m-d H:i:s"))
->or_where('library.available_until =', "00-00-00 00:00:00")
->group_end() //this will end grouping
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id')
Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
If anyone want to do this on page load w/ jQuery (sweet for search fields) here is my solution
jQuery.fn.focusAndSelect = function() {
return this.each(function() {
$(this).focus();
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
this.setSelectionRange(0, len);
} else {
$(this).val($(this).val());
}
this.scrollTop = 999999;
});
};
(function ($) {
$('#input').focusAndSelect();
})(jQuery);
Based on this post . Thanks to CSS-Tricks.com
public void Foo(IList<Bar> list)
{
// Do Something with the list here.
}
In this case you could pass in any class which implements the IList<Bar> interface. If you used List<Bar> instead, only a List<Bar> instance could be passed in.
The IList<Bar> way is more loosely coupled than the List<Bar> way.
A more clear usage might be to use switch parameters instead. Then, just the existence of the Unify parameter would mean it was set.
Like so:
param (
[int] $Turn,
[switch] $Unify
)
I have trouble wrapping my head around lambda expressions because I work in Visual FoxPro, which has Macro substitution and the ExecScript{} and Evaluate() functions, which seem to serve much the same purpose.
? Calculator(10, 23, "a + b")
? Calculator(10, 23, "a - b");
FUNCTION Calculator(a, b, op)
RETURN Evaluate(op)
One definite benefit to using formal lambdas is (I assume) compile-time checking: Fox won't know if you typo the text string above until it tries to run it.
This is also useful for data-driven code: you can store entire routines in memo fields in the database and then just evaluate them at run-time. This lets you tweak part of the application without actually having access to the source. (But that's another topic altogether.)
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
What's happening is that the shell is expanding "*test.c" into a list of files. Try escaping the asterisk as:
find . -name \*test.c
pd.to_numeric
with errors='coerce'
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use
pd.__version__ # '0.24.1' pd.to_numeric(s, errors='coerce').astype('Int32') 0 1 1 2 2 3 3 4 4 NaN dtype: Int32
There are other options to choose from as well, read the docs for more.
DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
Generally speaking, fixed section should be set with width
, height
and top
, bottom
properties, otherwise it won't recognise its size and position.
If the used box is direct child for body and has neighbours, then it makes sense to check z-index
and top, left
properties, since they could overlap each other, which might affect your mouse hover while scrolling the content.
Here is the solution for a content box (a direct child of body
tag) which is commonly used along with mobile navigation.
.fixed-content {
position: fixed;
top: 0;
bottom:0;
width: 100vw; /* viewport width */
height: 100vh; /* viewport height */
overflow-y: scroll;
overflow-x: hidden;
}
Hope it helps anybody. Thank you!
As of API 24, sending a file://
URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content://
URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION
flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
If you want to add N days to your days. You can use the plus operator as follows -
SELECT ( SYSDATE + N ) FROM DUAL;
This is certainly possible. This works in Chrome, Firefox, and IE 11 (and probably others).
focus();
var listener = window.addEventListener('blur', function() {
if (document.activeElement === document.getElementById('iframe')) {
// clicked
}
window.removeEventListener('blur', listener);
});
Caveat: This only detects the first click. As I understand, that is all you want.
I changed scrollable div to be with absolute position, and everything works for me
div.sidebar {
overflow: hidden;
background-color: green;
padding: 5px;
position: fixed;
right: 20px;
width: 40%;
top: 30px;
padding: 20px;
bottom: 30%;
}
div#fixed {
background: #76a7dc;
color: #fff;
height: 30px;
}
div#scrollable {
overflow-y: scroll;
background: lightblue;
position: absolute;
top:55px;
left:20px;
right:20px;
bottom:10px;
}
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
The $@
and $<
are special macros.
Where:
$@
is the file name of the target.
$<
is the name of the first dependency.
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.
So instead, you can use the xhr2 module. In other words:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
becomes:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
But ... of course, there are more popular modules like Axios, because -for example- uses promises:
// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
.btn:focus, .btn:active:focus, .btn.active:focus{
outline:none;
box-shadow:none;
}
This should remove outline and box shadow
If the variable is re-used within the same RUN
instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.
The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is because you specified http://file://
The http://
at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.
Note
If you link to something like
<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>
The above represents a link to a file called k:/yourfile.pdf
on the k: drive on the machine on which you are viewing the URL.
You can do this, for example the below creates a link to C:\temp\test.pdf
<a href="file:///C:/Temp/test.pdf">test.pdf</a>
By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.
Most people do not have a K:/ drive.
But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).
You could try
<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf
is a malformed
As of version 3.0.0, you can get the current route by calling:
this.context.router.location.pathname
Sample code is below:
var NavLink = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render() {
return (
<Link {...this.props}></Link>
);
}
});
Usage:
control.InvokeIfRequired(c => c.Visible = false);
return control.InvokeIfRequired(c => {
c.Visible = value
return c.Visible;
});
Code:
using System;
using System.ComponentModel;
namespace Extensions
{
public static class SynchronizeInvokeExtensions
{
public static void InvokeIfRequired<T>(this T obj, Action<T> action)
where T : ISynchronizeInvoke
{
if (obj.InvokeRequired)
{
obj.Invoke(action, new object[] { obj });
}
else
{
action(obj);
}
}
public static TOut InvokeIfRequired<TIn, TOut>(this TIn obj, Func<TIn, TOut> func)
where TIn : ISynchronizeInvoke
{
return obj.InvokeRequired
? (TOut)obj.Invoke(func, new object[] { obj })
: func(obj);
}
}
}
Just use "justify-content-center" in the row's class attribute.
<div class="container">
<div class="row justify-content-center">
<h1>This is a header</h1>
</div>
</div>
Add
PATH = C:\Program Files\Java\jdk1.8.0_66\bin
in Advanced system setting
. Then Choose Environment Variable.
select * from table where fiels1 NOT LIKE 'x' AND field2 NOT LIKE 'y'
//this work in case insensitive manner
Go to
Tools >> Options >> Text Editor >> C# >> IntelliSense
Under the Snippets behaviour section:
Make sure "Always include snippets" is selected.
I hope it works for you too.
if put 'http_errors' => false
in guzzle request options, then it would stop throw exception while get 4xx or 5xx error, like this: $client->get(url, ['http_errors' => false])
. then you parse the response, not matter it's ok or error, it would be in the response
for more info
I was having issues with mattdlockyer's solution because I was setting up popover links dynamically using code like this:
$('body').popover({
selector : '[rel="popover"]'
});
So I had to modify it like so. It fixed a lot of issues for me:
$('html').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('destroy');
}
});
});
Remember that destroy gets rid of the element, so the selector part is important on initializing the popovers.
The correct solution for this problem is to use display: table-cell
Important: This solution doesn't need float
since table-cell
already turns the div
into an element that lines up with the others in the same container. That also means you don't have to worry about clearing floats, overflow, background shining through and all the other nasty surprises that the float
hack brings along to the party.
CSS:
.container {
display: table;
}
.column {
display: table-cell;
width: 100px;
}
HTML:
<div class="container">
<div class="column">Column 1.</div>
<div class="column">Column 2 is a bit longer.</div>
<div class="column">Column 3 is longer with lots of text in it.</div>
</div>
Related:
easy
batch file:
FOR %%A IN (1 2 3) DO ECHO %%A
command line:
FOR %A IN (1 2 3) DO ECHO %A
output:
1
2
3
The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.
I try to change port number in the following file - /src/main/resources/application-prod.yml
And inside this file I made this change:
server: port: 8100 (or whatever you want)
I hope that this will works good for you
try this:
type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
var headers = XMLHttpRequest.getAllResponseHeaders();
}
Another way in addition to the ones provided here for ES6
module.exports = class TEST{
constructor(size) {
this.map = new MAp();
this.size = size;
}
get(key) {
return this.map.get(key);
}
length() {
return this.map.size;
}
}
and include the same as
var TEST= require('./TEST');
var test = new TEST(1);
Use Heredocs to output muli-line strings containing variables. The syntax is...
$string = <<<HEREDOC
string stuff here
HEREDOC;
The "HEREDOC" part is like the quotes, and can be anything you want. The end tag must be the only thing on it's line i.e. no whitespace before or after, and must end in a colon. For more info check out the manual.
You don't need to use bi-directional association instead of your code, you have just to add CascaType.Remove as a property to ManyToOne annotation, then use @OnDelete(action = OnDeleteAction.CASCADE), it's works fine for me.
My 2 cents contribution:
Besides removing the console warning (as shown above), it's best to remove yours logs from PROD environments (for security reasons). The best way I found to do so, is by adding this to nuxt.config.js
build: {
terser: {
terserOptions: {
compress: {
//this removes console.log from production environment
drop_console: true
}
}
}
}
How it works: Nuxt already uses terser as minifier. This config will force terser to ignore/remove all console logs commands during compression.
Move your row before <div class="container marketing">
and wrap it with a new container, because current container width is 1170px (not 100%):
<div class='hero'>
<div class="row">
...
</div>
</div>
CSS:
.hero {
background-color: #2ba6cb;
padding: 0 90px;
}
Works Fine for App Notification settings on IOS 10 (tested)
if(&UIApplicationOpenSettingsURLString != nil){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
Reflection is your friend, as has been pointed out. But you need to use the correct method;
Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined.
Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:
import pathlib
p = pathlib.Path('path/to/file')
if p.is_file(): # or p.is_dir() to see if it is a directory
# do stuff
You can (and usually should) still use a try/except
block when opening files:
try:
with p.open() as f:
# do awesome stuff
except OSError:
print('Well darn.')
The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:
# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2
Then import it as follows:
# Older Python versions
import pathlib2 as pathlib
I was also having problem with starting MySql server but run command as mention right mark in picture . Its working fine .
As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.
http://developer.android.com/reference/android/util/JsonReader.html
Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.
When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:
SELECT object_name(16003073)
EDIT :
There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
If you are really concerned about speed and not worried about the data you can do a Truncate. But this is assuming your DataTable is on a database and not just a memory object.
TRUNCATE TABLE tablename
The difference is this removes all rows without logging the row deletes making the transaction faster.
Requirements:
Worked great without restart on Xcode 10
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.
On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:
You can do it without telling the full Acrobat path, like this:
Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();
If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:
myProcess.StartInfo.FileName = "Acrobat.exe";
You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.
Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
You should be able to access the local database by using the name localhost
. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect
. See http://php.net/manual/en/function.mysql-connect.php.
Overall:
Both PUT and POST can be used for creating.
You have to ask, "what are you performing the action upon?", to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST, then you would do that to a list of questions. If you want to use PUT, then you would do that to a particular question.
Great, both can be used, so which one should I use in my RESTful design:
You do not need to support both PUT and POST.
Which you use is up to you. But just remember to use the right one depending on what object you are referencing in the request.
Some considerations:
An example:
I wrote the following as part of another answer on SO regarding this:
POST:
Used to modify and update a resource
POST /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Note that the following is an error:
POST /questions/<new_question> HTTP/1.1 Host: www.example.com/
If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a 'resource not found' error because
<new_question>
does not exist yet. You should PUT the<new_question>
resource on the server first.You could though do something like this to create a resources using POST:
POST /questions HTTP/1.1 Host: www.example.com/
Note that in this case the resource name is not specified, the new objects URL path would be returned to you.
PUT:
Used to create a resource, or overwrite it. While you specify the resources new URL.
For a new resource:
PUT /questions/<new_question> HTTP/1.1 Host: www.example.com/
To overwrite an existing resource:
PUT /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),
4.3.4. PUT
The PUT method requests that the state of the target resource be
created
orreplaced
with the state defined by the representation enclosed in the request message payload.
I run into the same problem with linker complaining about the main executable missing. This happened during our solution port to the new Visual Studio 2013. The solution is a varied mix of managed and un-managed projects/code. The problem (and fix) ended up being a missing app.config file in the solution folder. Took a day to figure this one out :(, as output log was not very helpful.
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Bootstrap 2.3.x and later supports the dropdown-submenu
..
<ul class="dropdown-menu">
<li><a href="#">Login</a></li>
<li class="dropdown-submenu">
<a tabindex="-1" href="#">More options</a>
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
</ul>
</li>
<li><a href="#">Logout</a></li>
</ul>
That is possible, of course.
for databaseName in a b c d e f; do
# do something like: echo $databaseName
done
See Bash Loops for, while and until for details.
When you use Vector *one
you are merely creating a pointer to the structure but there is no memory allocated to it.
Simply use one = (Vector *)malloc(sizeof(Vector));
to declare memory and instantiate it.
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
Any Error
object has a stack
member that traps the point at which it was constructed.
var stack = new Error().stack
console.log( stack )
or more simply:
console.trace("Here I am!")
I got this same error because part of the PK was a datetime column, and the record being inserted used DateTime.Now as the value for that column. Entity framework would insert the value with millisecond precision, and then look for the value it just inserted also with millisecond precision. However SqlServer had rounded the value to second precision, and thus entity framework was unable to find the millisecond precision value.
The solution was to truncate the milliseconds from DateTime.Now before inserting.
According to the updated syntax, you can use this.myRref.current.focus()
All these answers are superficially correct. However, the proper answer is
apropos disk # And pray your admin maintains the whatis database
because asking questions the answers of which lay at your fingertips in the manual wastes everybody's time.
ng-init
does not work when you are assigning variables inside loop. Use
{{myVariable=whatever;""}}
The trailing ""
stops the Angular expression being evaluated to any text.
Then you can simply call {{myVariable}}
to output your variable value.
I found this very useful when iterating multiple nested arrays and I wanted to keep my current iteration info in one variable instead of querying it multiple times.
console.log
logs debug information to the console on some browsers (Firefox with Firebug installed, Chrome, IE8, anything with Firebug Lite installed). On Firefox it is a very powerful tool, allowing you to inspect objects or examine the layout or other properties of HTML elements. It isn't related to jQuery, but there are two things that are commonly done when using it with jQuery:
install the FireQuery extension for Firebug. This, amongst other advantages, makes the logging of jQuery objects look nicer.
create a wrapper that is more in line with jQuery's chaining code conventions.
This means usually something like this:
$.fn.log = function() {
if (window.console && console.log) {
console.log(this);
}
return this;
}
which you can then invoke like
$('foo.bar').find(':baz').log().hide();
to easily check inside jQuery chains.
Instead of mysql_connect use mysqli_connect.
mysqli is provide a functionality for connect multiple database at a time.
$Db1 = new mysqli($hostname,$username,$password,$db_name1);
// this is connection 1 for DB 1
$Db2 = new mysqli($hostname,$username,$password,$db_name2);
// this is connection 2 for DB 2
Facing this problem, I made the following addition to my css stylesheet:
#mainContent .container {
padding-left:16px;
padding-right:16px;
}
#mainContent .row {
margin-left: -8px;
margin-right: -8px;
}
#mainContent .col-xs-1, #mainContent .col-sm-1, #mainContent .col-md-1, #mainContent .col-lg-1, #mainContent .col-xs-2, #mainContent .col-sm-2, #mainContent .col-md-2, #mainContent .col-lg-2, #mainContent .col-xs-3, #mainContent .col-sm-3, #mainContent .col-md-3, #mainContent .col-lg-3, #mainContent .col-xs-4, #mainContent .col-sm-4, #mainContent .col-md-4, #mainContent .col-lg-4, #mainContent .col-xs-5, #mainContent .col-sm-5, #mainContent .col-md-5, #mainContent .col-lg-5, #mainContent .col-xs-6, #mainContent .col-sm-6, #mainContent .col-md-6, #mainContent .col-lg-6, #mainContent .col-xs-7, #mainContent .col-sm-7, #mainContent .col-md-7, #mainContent .col-lg-7, #mainContent .col-xs-8, #mainContent .col-sm-8, #mainContent .col-md-8, #mainContent .col-lg-8, #mainContent .col-xs-9, #mainContent .col-sm-9, #mainContent .col-md-9, #mainContent .col-lg-9, #mainContent .col-xs-10, #mainContent .col-sm-10, #mainContent .col-md-10, #mainContent .col-lg-10, #mainContent .col-xs-11, #mainContent .col-sm-11, #mainContent .col-md-11, #mainContent .col-lg-11, #mainContent .col-xs-12, #mainContent .col-sm-12, #mainContent .col-md-12, #mainContent .col-lg-12
{
padding-left: 8px;
padding-right: 8px;
}
This overrides the default bootstrap styling and makes the left and right sides and the gutter equal width.
To export all documents from ElasticSearch into JSON, you can use the esbackupexporter tool. It works with index snapshots. It takes the container with snapshots (S3, Azure blob or file directory) as the input and outputs one or several zipped JSON files per index per day. It is quite handy when exporting your historical snapshots. To export your hot index data, you may need to make the snapshot first (see the answers above).
In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.
From http://en.wikipedia.org/wiki/Declarative_programming
in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )
A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.
When you write the statement
*src = "anotherstring";
the compiler sees the constant string "abcdefghijklmnop"
like an array. Imagine you had written the following code instead:
char otherstring[14] = "anotherstring";
...
*src = otherstring;
Now, it's a bit clearer what is going on. The left-hand side, *src
, refers to a char
(since src
is of type pointer-to-char
) whereas the right-hand side, otherstring
, refers to a pointer.
This isn't strictly forbidden because you may want to store the address that a pointer points to. However, an explicit cast is normally used in that case (which isn't too common of a case). The compiler is throwing up a red flag because your code is likely not doing what you think it is.
It appears to me that you are trying to assign a string. Strings in C aren't data types like they are in C++ and are instead implemented with char
arrays. You can't directly assign values to a string like you are trying to do. Instead, you need to use functions like strncpy
and friends from <string.h>
and use char
arrays instead of char
pointers. If you merely want the pointer to point to a different static string, then drop the *
.
This should work:
.panel > .panel-heading {
background-image: none;
background-color: red;
color: white;
}
Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint()
to: createCompactFormat()
public String unPrettyPrint(final String xml){
if (StringUtils.isBlank(xml)) {
throw new RuntimeException("xml was null or blank in unPrettyPrint()");
}
final StringWriter sw;
try {
final OutputFormat format = OutputFormat.createCompactFormat();
final org.dom4j.Document document = DocumentHelper.parseText(xml);
sw = new StringWriter();
final XMLWriter writer = new XMLWriter(sw, format);
writer.write(document);
}
catch (Exception e) {
throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
}
return sw.toString();
}
I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:
debug: coratools_debug
devenv coralib.vcproj /build debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
You can also use the msbuild tool to do the same thing:
debug: coratools_debug
msbuild coralib.vcxproj /p:Configuration=debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.
You need to set an own WebViewClient for your WebView by extending the WebViewClient class.
You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).
More guidance for this topic can be found in Google's WebView tutorial
I was facing the same problem, unable to create directory on Galaxy S but was able to create it successfully on Nexus and Samsung Droid. How I fixed it was by adding following line of code:
File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
dir.mkdirs();
My problem was, that Visual Studio somehow automatically lowercased *ngFor
to *ngfor
on copy&paste.
You can also explicitly tell maven which java version to compile for. You can try adding the maven-compiler-plugin
to your pom.
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
[...]
</build>
[...]
</project>
If you imported a maven project into an IDE, then there is probably a maven setting in your IDE for default compiler that your maven runner is using.
I don't have much experience than above users but I faced this same issue and I Solved this with below Solution
<Button
android:id="@+id/btnRemove"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btnEdit"
android:layout_weight="1"
android:background="@drawable/btn"
android:text="@string/remove"
android:onClick="btnRemoveClick"
/>
btnRemoveClick Click event
public void btnRemoveClick(View v)
{
final int position = listviewItem.getPositionForView((View) v.getParent());
listItem.remove(position);
ItemAdapter.notifyDataSetChanged();
}
I was using an external build utility. Think of something like Ants, if I understand the product correctly, just a commercial version. I had to contact the manufacturer for the answer.
As it turns out, there is a global macro in the project, DEVSTUDIO_NET_DIR. I had to change the path to .Net there. They list various visual studio versions as "Actions", which through me off, but all roads lead back to that one global variable behind the scenes. I would list that as a defect against the product, if I had my way, unless I am missing something in my understanding. Correcting the path there fixed the build problem.
You can try the following method(python3.6.2):
case one:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
response = make_response('<h1>hello world</h1>',301)
response.headers = headers
return response
case two:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
return '<h1>hello world</h1>',301,headers
I am using Flask .And if you want to return json,you can write this:
import json #
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return json.dumps(result),200,{'content-type':'application/json'}
from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return jsonify(result)
In a nutshell, Forking is perhaps the same as "cloning under your GitHub ID/profile". A fork is anytime better than a clone, with a few exceptions, obviously. The forked repository is always being monitored/compared with the original repository unlike a cloned repository. That enables you to track the changes, initiate pull requests and also manually sync the changes made in the original repository with your forked one.
READY TO USE FUNCTION (using Promise)
/**
* Select file(s).
* @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
* @param {Boolean} multiple Indicates if the user can select multiples file.
* @returns {Promise<File|File[]>} A promise of a file or array of files in case the multiple parameter is true.
*/
function (contentType, multiple){
return new Promise(resolve => {
let input = document.createElement('input');
input.type = 'file';
input.multiple = multiple;
input.accept = contentType;
input.onchange = _ => {
let files = Array.from(input.files);
if (multiple)
resolve(files);
else
resolve(files[0]);
};
input.click();
});
}
TEST IT
// Content wrapper element_x000D_
let contentElement = document.getElementById("content");_x000D_
_x000D_
// Button callback_x000D_
async function onButtonClicked(){_x000D_
let files = await selectFile("image/*", true);_x000D_
contentElement.innerHTML = files.map(file => `<img src="${URL.createObjectURL(file)}" style="width: 100px; height: 100px;">`).join('');_x000D_
}_x000D_
_x000D_
// ---- function definition ----_x000D_
function selectFile (contentType, multiple){_x000D_
return new Promise(resolve => {_x000D_
let input = document.createElement('input');_x000D_
input.type = 'file';_x000D_
input.multiple = multiple;_x000D_
input.accept = contentType;_x000D_
_x000D_
input.onchange = _ => {_x000D_
let files = Array.from(input.files);_x000D_
if (multiple)_x000D_
resolve(files);_x000D_
else_x000D_
resolve(files[0]);_x000D_
};_x000D_
_x000D_
input.click();_x000D_
});_x000D_
}
_x000D_
<button onclick="onButtonClicked()">Select images</button>_x000D_
<div id="content"></div>
_x000D_
I just used =COUNTIF(Range, "<>")
and it counted non-empty cells for me.
For anyone still experiencing this, I found that images served on Amazon S3 do not work for WhatsApp mobile app (both Android and iOS, but Mac desktop app was fine). It's very possible that our AWS settings cause this, but I noticed the pattern in other sites as well (e.g. this one with an og:image
hitting a domain like https://s3.amazonaws.com
).
There were no problems on any other platform I tried, just WhatsApp mobile apps. As soon as I pointed my <meta property="og:image" content="https://some-non-aws-location" />
to another public URL like a Google Drive file (shared publicly of course), it worked fine.
I also tried committing the image in our repo, which is hosted and deployed on AWS with a custom domain, and that didn't work either. So AWS still seems to be the culprit. Hope this helps someone!
Self-contained example
Same technique as in this answer but:
Source:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Notification notification = new Notification.Builder(Main.this)
/* Make app open when you click on the notification. */
.setContentIntent(PendingIntent.getActivity(
Main.this,
Main.this.i,
new Intent(Main.this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT))
.setContentTitle("title")
.setAutoCancel(true)
.setContentText(String.format("id = %d", Main.this.i))
// Starting on Android 5, only the alpha channel of the image matters.
// https://stackoverflow.com/a/35278871/895245
// `android.R.drawable` resources all seem suitable.
.setSmallIcon(android.R.drawable.star_on)
// Color of the background on which the alpha image wil drawn white.
.setColor(Color.RED)
.build();
final NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Main.this.i, notification);
// If the same ID were used twice, the second notification would replace the first one.
//notificationManager.notify(0, notification);
Main.this.i++;
}
});
this.setContentView(button);
}
}
Tested in Android 22.
import urllib2
from bs4 import BeautifulSoup
a=urllib2.urlopen('http://dir.yahoo.com')
code=a.read()
soup=BeautifulSoup(code)
links=soup.findAll("a")
#To get href part alone
print links[0].attrs['href']
Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.
Entity
VehicleInfoEntities db = new VehicleInfoEntities();
Stored Procedure
dbo.prcGetMakes()
or
you can add any parameters in your stored procedure inside the brackets ()
dbo.prcGetMakes("BMW")
Controller
public class HomeController : Controller
{
VehicleInfoEntities db = new VehicleInfoEntities();
public ActionResult Index()
{
var makes = db.prcGetMakes(null);
return View(makes);
}
}
Service
extends ContextWrapper
which extends Context
. Hence the Service
is a Context
.
Use 'this'
keyword in the service.
HashMap
basically contains Entry
which subsequently contains Key(Object)
and Value(Object)
.Internally HashSet
are HashMap
and HashMap
do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap
keeps its value as key in the underlying HashMap
and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).
Look at the below code for HashSet Class:
public boolean [More ...] add(E e) {
return map.put(e, PRESENT)==null;
}
Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.
As far as I have understood your question, you have listed two issues.
PROBLEM 1:
You are not able to execute the Python scripts by double clicking the Python file in Windows.
REASON:
The script runs too fast to be seen by the human eye.
SOLUTION:
Add input()
in the bottom of your script and then try executing it with double click. Now the cmd will be open until you close it.
EXAMPLE:
print("Hello World")
input()
PROBLEM 2:
./
issue
SOLUTION:
Use Tab to autocomplete the filenames rather than manually typing the filename with ./
autocomplete automatically fills all this for you.
USAGE:
CD into the directory in which .py
files are present and then assume the filename is test.py
then type python te
and then press Tab, it will be automatically converted to python ./test.py
.
Reflection; for an instance:
obj.GetType().GetProperties();
for a type:
typeof(Foo).GetProperties();
for example:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
Following feedback...
null
as the first argument to GetValue
GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
(which returns all public/private instance properties ).I made a one-liner out of @JohnL's solution:
$MyInvocation.MyCommand.Path | Split-Path | Push-Location
The proj.4 software provides a command line program that can do the conversion, e.g.
LAT=40
LON=-110
echo $LON $LAT | cs2cs +proj=latlong +datum=WGS84 +to +proj=geocent +datum=WGS84
It also provides a C API. In particular, the function pj_geodetic_to_geocentric
will do the conversion without having to set up a projection object first.
Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.
I little sophisticated way:
$(selector).is(condition)? alert('true') : alert('false');
Ex:
$("#btn-primary").is(":disabled")? alert('button disabled') : alert('button disabled');
I had the same issue. Sublime3 no longer shows all of the installed packages when you choose Show Packages from the Preferences Menu.
To customise a colour scheme do the following (UNIX):
--- EDIT ---
For Mac OS X the themes are stored in zipped files so although the preferences file shows them as being in Packages/Color Scheme - Default/ they don't appear in that directory unless you extract them.
for example
"color_scheme": "Packages/Color Scheme - Legacy/myTheme.tmTheme"
Check if the data attribute is present, then do the stuff...
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});
My Settings Screenshot:
Thanks to this post.
Just turn off instant run in your settings. You can easily search the keyword "instant" like I showed and it would switch to the window you want.
The cool thing about anaconda is, that you can manage virtual environments for several projects. Those also have the benefit of keeping several python installations apart. This could be a problem when several installations of a module or package are interfering with each other.
Try the following:
user@machine:~$ conda create -n pandas_env python=2.7
user@machine:~$ source activate pandas_env
on Linux/OSX or $ activate pandas_env
on Windows. On Linux the active environment is shown in parenthesis in front of the user name in the shell. (I am not sure how windows handles this, but you can see it by typing $ conda info -e
. The one with the * next to it is the active one)(pandas_env)user@machine:~$ conda list
to show a list of all installed modules.(pandas_env)user@machine:~$ conda install pandas
, as @Fiabetto suggested.(pandas_env)user@machine:~$ python
and try to load pandas again. Note that now you are working in a python environment, that only knows the modules installed inside the pandas_env
environment. Every time you want to use it you have to activate the environment. This might feel a little bit clunky at first, but really shines once you have to manage different versions of python (like 2.7 or 3.4) or you need a specific version of a module (like numpy 1.7).
If this still does not work you have several options:
Check if the right pandas module is found:
`(pandas_env)user@machine:~$ python`
Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
>>> import imp
>>> imp.find_module("pandas")
(None, '/path/to/miniconda3/envs/foo/lib/python2.7/site-packages/pandas', ('', '', 5))
# See what this returns on your system.
Reinstall pandas in your environment with $ conda install -f pandas
. This might help if you files have been corrupted somehow.
pip
). To do this, create a new environment like above (make sure to pick a different name to avoid clashes here) but replace point 4 by (pandas_env)user@machine:~$ pip install pandas
.I've posted this comment on a seperate StackOverflow thread, but thought it was worth repeating here:
For our in-house ASP.Net app, adding the "X-UA-Compatible" tag on the web page, in the web.config or in the code-behind made absolutely no difference.
The only thing that worked for us was to manually turn off this setting in IE8:
(Sigh.)
This problem only seems to happen with IE8 & IE9 on intranet sites. External websites will work fine and use the correct version of IE8/9, but for internal websites, IE9 suddenly decides it's actually IE7, and doesn't have any HTML 5 support.
No, I don't quite understand this logic either.
My reluctant solution has been to test whether the browser has HTML 5 support (by creating a canvas, and testing if it's valid), and displaying this message to the user if it's not valid:
It's not particularly user-friendly, but getting the user to turn off this annoying setting seems to be the only way to let them run in-house HTML 5 web apps properly.
Or get the users to use Chrome. ;-)
in Eclipse 4.4.1
com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
Try this for revert all changes uncommited in local branch
$ git reset --hard HEAD
But if you see a error like this:
fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.
You can navigate to '.git' folder then delete index.lock file:
$ cd /directory/for/your/project/.git/
$ rm index.lock
Finaly, run again the command:
$ git reset --hard HEAD
There are non-obvious memory retention issues to take into account here. Since a non-static inner class maintains an implicit reference to it's 'outer' class, if an instance of the inner class is strongly referenced, then the outer instance is strongly referenced too. This can lead to some head-scratching when the outer class is not garbage collected, even though it appears that nothing references it.
The static
keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.
Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.
You could do this: <a href="">This page</a>
but I don't think it preserves GET and POST data.
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
To pass the parameter you need to use resolve and inject the items in controller
$scope.Edit = function (Id) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: 'EditCtrl',
resolve: {
editId: function () {
return Id;
}
}
});
}
Now if you will use like this:
app.controller('EditCtrl', ['$scope', '$location'
, function ($scope, $location, editId)
in this case editId will be undefined. You need to inject it, like this:
app.controller('EditCtrl', ['$scope', '$location', 'editId'
, function ($scope, $location, editId)
Now it will work smooth, I face the same problem many time, once injected, everything start working!
Besides the registry mods, you may need to change version of the .net sdk your settings set to in Visual Studio.
I was having this problem and decided to check the project debug settings.
Project => Toolbar Properties => Debug Advance Compile Options button
The Target Framework (all configurations) was set to 3.0 which is not on my system.
I changed that to 4.0, then had to restart the project and Visual Studio 2010.
The project then built without errors and ran.
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
Did a little research on this, it appears that you are looping from 1 to 2147483647, in increments of 1.
(1, 1, 2147483647): The firs number is the starting number, the next number is the step, and the last number is the end number.
Edited To Add
It appears that the loop runs to completion regardless of any test conditions. I tested
FOR /L %%F IN (1, 1, 5) DO SET %%F=6
And it ran very quickly.
Second Edit
Since this is the only line in the batch file, you might try the EXIT command:
FOR /L %%F IN (1, 1, 2147483647) DO @IF NOT EXIST %%F EXIT
However, this will also close the DOS prompt window.
http://code.google.com/p/javascript-number-formatter/ :
UPDATE
As say Tomáš Zato here one line solution:
(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])
which described in ECMA-262 5.1 Edition:
and will work in future versions of browsers...
Whenever a TypeInitializationException
is thrown, check all initialization logic of the type you are referring to for the first time in the statement where the exception is thrown - in your case: Logger
.
Initialization logic includes: the type's static constructor (which - if I didn't miss it - you do not have for Logger
) and field initialization.
Field initialization is pretty much "uncritical" in Logger
except for the following lines:
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_commonAppData
is null
at the point where Path.Combine(s_commonAppData, "XXXX");
is called. As far as I'm concerned, these initializations happen in the exact order you wrote them - so put s_commonAppData
up by at least two lines ;)
As of Laravel 5.8.15 the query builder now has dd
and dump
methods so you can do
DB::table('data')->where('a', 1)->dump();
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {_x000D_
dvcontainer = grecaptcha.render('dvCaptcha', {_x000D_
'sitekey': ReCaptchSiteKey,_x000D_
'expired-callback' :function (response){_x000D_
recaptch.reset();_x000D_
c_responce = null;_x000D_
},_x000D_
'callback': function (response) {_x000D_
$("[id*=txtCaptcha]").val(c_responce);_x000D_
$("[id*=rfvCaptcha]").hide();_x000D_
c_responce = response;_x000D_
_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
function callonanybuttonClick(){_x000D_
_x000D_
if (c_responce == null) {_x000D_
$("[id*=txtCaptcha]").val("");_x000D_
$("[id*=rfvCaptcha]").show();_x000D_
_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
$("[id*=txtCaptcha]").val(c_responce);_x000D_
$("[id*=rfvCaptcha]").hide();_x000D_
return true;_x000D_
}_x000D_
_x000D_
}
_x000D_
<div id="dvCaptcha" class="captchdiv"></div>_x000D_
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />_x000D_
<label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
_x000D_
Captcha validation is required.
To have it send it as a CSV and have it give the file name, use header():
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.
If you have two servers on the same domain (eg. APP and DB), you can also use Windows Authentication between the app and MSSQL by setting up local users on both machines that match (same username and password). If you don't have the passwords matched up, it can throw this error.
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime()
which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
My problem was int Main() instead of int main()
good luck
0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:
>>> int('010101', 0)
4161
If you don't start with a 0, then python assumes the number is base 10.
>>> int('10101', 0)
10101
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:
ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);
LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();
localServer.start();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509Certificate cert: chain) {
System.err.println(cert);
}
return false;
}
};
SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
trustStrategy, new AllowAllHostnameVerifier());
Scheme https = new Scheme("https", 443, sslsf);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
InetSocketAddress address = localServer.getServiceAddress();
HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
HttpGet httpget1 = new HttpGet("/random/100");
HttpResponse response1 = httpclient.execute(target1, httpget1);
System.err.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
HttpGet httpget2 = new HttpGet("/");
HttpResponse response2 = httpclient.execute(target2, httpget2);
System.err.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
localServer.stop();
}
Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.
Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.
[
[
Version: V1
Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
y:
f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e
Validity: [From: Sat Dec 11 14:48:35 CET 2004,
To: Tue Dec 09 14:48:35 CET 2014]
Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 41bafab3]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3
]
HTTP/1.1 200 OK
[
[
Version: V3
Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
public exponent: 65537
Validity: [From: Wed May 26 02:00:00 CEST 2010,
To: Sat May 26 01:59:59 CEST 2012]
Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[accessMethod: 1.3.6.1.5.5.7.48.1
accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]
...
]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...
There is a far easier solution (IMO) in Bootstrap 3 that does not require you to compile any custom LESS. You just have to leverage the cascade in "Cascading Style Sheets."
Set up your CSS loading like so...
<link type="text/css" rel="stylesheet" href="/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/css/custom.css" />
Where /css/custom.css
is your unique style definitions. Inside that file, add the following definition...
@media (min-width: 1200px) {
.container {
width: 970px;
}
}
This will override Bootstrap's default width: 1170px
setting when the viewport is 1200px or bigger.
Tested in Bootstrap 3.0.2
Raj_89 solution is the closest to being valid option altough as mentioned by Kevin Swarts in comment it is going to break IE, which for large number of corporate client is an issue (and telling your client that you won't code for IE "because reasons" is unlikely to make your boss happy ;) ).
So I played around with it and here is the problem: the 'onmousedown' event is throwing a fit in IE, so what we want to do, is to prevent default when user clicks the dropdown for the first time. It is important this is only time we do this: if we prevent defult on the next click, when user makes his pick, the onchange event won't fire.
This way we get nice dropdown, no flicker, no breaking down IE - just works... well at least in IE10 and up, and latest relases of all the other major browsers.
<p>Which is the most annoing browser of them all:</p>
<select id="sel" size = "1">
<option></option>
<option>IE 9</option>
<option>IE 10</option>
<option>Edge</option>
<option>Firefox</option>
<option>Chrome</option>
<option>Opera</option>
</select>
Here is the fiddle: https://jsfiddle.net/88cxzhom/27/
Few more things to notice: 1) The absolute positioning and setting z-index is helpful to avoid moving other elements when the options are displayed. 2) Use 'currentTarget' property - this will be the select element across all browsers. While 'target' will be select in IE, the rest will actually allow you to work with option.
Hope this helps someone.
print str(count) + ' ' + str(conv)
- This did not work. However, replacing +
with ,
works for me
The error means the OS of the listening socket recognized the inbound connection request but chose to intentionally reject it.
Assuming an intermediate firewall is not getting in the way, there are only two reasons (that I know of) for the OS to reject an inbound connection request. One reason has already been mentioned several times - the listening port being connected to is not open.
There is another reason that has not been mentioned yet - the listening port is actually open and actively being used, but its backlog of queued inbound connection requests has reached its maximum so there is no room available for the inbound connection request to be queued at that moment. The server code has not called accept() enough times yet to finish clearing out available slots for new queue items.
Wait a moment or so and try the connection again. Unfortunately, there is no way to differentiate between "the port is not open at all" and "the port is open but too busy right now". They both use the same generic error code.
To use the Combobox
in the way you intend, you could pass in an object to the cmbTripName.Items.Add
method.
That object should have FleetID
and FleetName
properties:
while (drd.Read())
{
cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
The Fleet
Class:
class Fleet
{
public Fleet(string fleetId, string fleetName)
{
FleetId = fleetId;
FleetName = fleetName
}
public string FleetId {get;set;}
public string FleetName {get;set;}
}
Or, You could probably do away with the need for a Fleet
class completely by using an anonymous type...
while (drd.Read())
{
cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
IIS will create it again AFAIK.
You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:
select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual
Add this before you call method invoke:
while (!this.IsHandleCreated)
System.Threading.Thread.Sleep(100)
You can use option:selected
to get the chosen option of the select
element, then the text()
method:
$("select option:selected").text();
Here's an example:
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value="1">Volvo</option>_x000D_
<option value="2" selected="selected">Saab</option>_x000D_
<option value="3">Mercedes</option>_x000D_
</select>
_x000D_
The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.
How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
You need a click listener which calls addActivityItem
if less than 2 options exist:
var activities = document.getElementById("activitySelector");
activities.addEventListener("click", function() {
var options = activities.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
addActivityItem();
}
});
activities.addEventListener("change", function() {
if(activities.value == "addNew")
{
addActivityItem();
}
});
function addActivityItem() {
// ... Code to add item here
}
A live demo is here on JSfiddle.
Here's another option for debugging purposes.
Be sure never to use this in any production environment, as it will negate benefits of using SSL in the first place. It is only ever valid to do this in your local development environment.
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):
select *
from calls c join users u
on c.assigned_to = u.user_id
or c.requestor_id = u.user_id
where u.dept = 4
HTMLDocument DOC = this.MySuperBrowser.Document as HTMLDocument;
public IHTMLAnchorElement imageElementHref;
imageElementHref = DOC.getElementById("idfirsticonhref") as IHTMLAnchorElement;
Simply try this code
Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial
keyword.
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
If you are trying to change a value after the form was submitted, you can use something like:
if form.is_valid():
form.cleaned_data['Email'] = GetEmailString()
Check the referenced docs above for more on using cleaned_data
Mostly, those restrictions are in place because of language designers. The underlying justification may be compatibility with languange history, ideals, or simplification of compiler design.
The compiler may (and does) choose to:
The switch statement IS NOT a constant time branch. The compiler may find short-cuts (using hash buckets, etc), but more complicated cases will generate more complicated MSIL code with some cases branching out earlier than others.
To handle the String case, the compiler will end up (at some point) using a.Equals(b) (and possibly a.GetHashCode() ). I think it would be trival for the compiler to use any object that satisfies these constraints.
As for the need for static case expressions... some of those optimisations (hashing, caching, etc) would not be available if the case expressions weren't deterministic. But we've already seen that sometimes the compiler just picks the simplistic if-else-if-else road anyway...
Edit: lomaxx - Your understanding of the "typeof" operator is not correct. The "typeof" operator is used to obtain the System.Type object for a type (nothing to do with its supertypes or interfaces). Checking run-time compatibility of an object with a given type is the "is" operator's job. The use of "typeof" here to express an object is irrelevant.
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str;
str.sprintf("%s %d", "string", 213);
try "configuration properties -> debugging -> environment" and set the PATH variable in run-time
Try this:
$NameRegex = "chalmw-dm"
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}
For Python 3:
>>> exec(open("helloworld.py").read())
Make sure that you're in the correct directory before running the command.
To run a file from a different directory, you can use the below command:
with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
exec(file.read())
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Also possible to use:
pkill -f "Process name"
For me, it worked up perfectly. It was what I have been looking for. pkill doesn't work with name without the flag.
When -f
is set, the full command line is used for pattern matching.
This will work if your route looks like this: localhost:8888/p?tagid=1234
var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234
Otherwise use the following code if your route looks like this: localhost:8888/p/1234
var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234
One I can answer confidently!
DateTime expiryDate = DateTime.Now.AddDays(30);
Or possibly - if you just want the date without a time attached which might be more appropriate:
DateTime expiryDate = DateTime.Today.AddDays(30);
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`