A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:
Save this files and use
(function(window){_x000D_
_x000D_
var WORKER_PATH = 'recorderWorker.js';_x000D_
var Recorder = function(source, cfg){_x000D_
var config = cfg || {};_x000D_
var bufferLen = config.bufferLen || 4096;_x000D_
this.context = source.context;_x000D_
this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
worker.postMessage({_x000D_
command: 'init',_x000D_
config: {_x000D_
sampleRate: this.context.sampleRate_x000D_
}_x000D_
});_x000D_
var recording = false,_x000D_
currCallback;_x000D_
_x000D_
this.node.onaudioprocess = function(e){_x000D_
if (!recording) return;_x000D_
worker.postMessage({_x000D_
command: 'record',_x000D_
buffer: [_x000D_
e.inputBuffer.getChannelData(0),_x000D_
e.inputBuffer.getChannelData(1)_x000D_
]_x000D_
});_x000D_
}_x000D_
_x000D_
this.configure = function(cfg){_x000D_
for (var prop in cfg){_x000D_
if (cfg.hasOwnProperty(prop)){_x000D_
config[prop] = cfg[prop];_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
this.record = function(){_x000D_
_x000D_
recording = true;_x000D_
}_x000D_
_x000D_
this.stop = function(){_x000D_
_x000D_
recording = false;_x000D_
}_x000D_
_x000D_
this.clear = function(){_x000D_
worker.postMessage({ command: 'clear' });_x000D_
}_x000D_
_x000D_
this.getBuffer = function(cb) {_x000D_
currCallback = cb || config.callback;_x000D_
worker.postMessage({ command: 'getBuffer' })_x000D_
}_x000D_
_x000D_
this.exportWAV = function(cb, type){_x000D_
currCallback = cb || config.callback;_x000D_
type = type || config.type || 'audio/wav';_x000D_
if (!currCallback) throw new Error('Callback not set');_x000D_
worker.postMessage({_x000D_
command: 'exportWAV',_x000D_
type: type_x000D_
});_x000D_
}_x000D_
_x000D_
worker.onmessage = function(e){_x000D_
var blob = e.data;_x000D_
currCallback(blob);_x000D_
}_x000D_
_x000D_
source.connect(this.node);_x000D_
this.node.connect(this.context.destination); //this should not be necessary_x000D_
};_x000D_
_x000D_
Recorder.forceDownload = function(blob, filename){_x000D_
var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
var link = window.document.createElement('a');_x000D_
link.href = url;_x000D_
link.download = filename || 'output.wav';_x000D_
var click = document.createEvent("Event");_x000D_
click.initEvent("click", true, true);_x000D_
link.dispatchEvent(click);_x000D_
}_x000D_
_x000D_
window.Recorder = Recorder;_x000D_
_x000D_
})(window);_x000D_
_x000D_
//ADDITIONAL JS recorderWorker.js_x000D_
var recLength = 0,_x000D_
recBuffersL = [],_x000D_
recBuffersR = [],_x000D_
sampleRate;_x000D_
this.onmessage = function(e){_x000D_
switch(e.data.command){_x000D_
case 'init':_x000D_
init(e.data.config);_x000D_
break;_x000D_
case 'record':_x000D_
record(e.data.buffer);_x000D_
break;_x000D_
case 'exportWAV':_x000D_
exportWAV(e.data.type);_x000D_
break;_x000D_
case 'getBuffer':_x000D_
getBuffer();_x000D_
break;_x000D_
case 'clear':_x000D_
clear();_x000D_
break;_x000D_
}_x000D_
};_x000D_
_x000D_
function init(config){_x000D_
sampleRate = config.sampleRate;_x000D_
}_x000D_
_x000D_
function record(inputBuffer){_x000D_
_x000D_
recBuffersL.push(inputBuffer[0]);_x000D_
recBuffersR.push(inputBuffer[1]);_x000D_
recLength += inputBuffer[0].length;_x000D_
}_x000D_
_x000D_
function exportWAV(type){_x000D_
var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
var interleaved = interleave(bufferL, bufferR);_x000D_
var dataview = encodeWAV(interleaved);_x000D_
var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
this.postMessage(audioBlob);_x000D_
}_x000D_
_x000D_
function getBuffer() {_x000D_
var buffers = [];_x000D_
buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
this.postMessage(buffers);_x000D_
}_x000D_
_x000D_
function clear(){_x000D_
recLength = 0;_x000D_
recBuffersL = [];_x000D_
recBuffersR = [];_x000D_
}_x000D_
_x000D_
function mergeBuffers(recBuffers, recLength){_x000D_
var result = new Float32Array(recLength);_x000D_
var offset = 0;_x000D_
for (var i = 0; i < recBuffers.length; i++){_x000D_
result.set(recBuffers[i], offset);_x000D_
offset += recBuffers[i].length;_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
function interleave(inputL, inputR){_x000D_
var length = inputL.length + inputR.length;_x000D_
var result = new Float32Array(length);_x000D_
_x000D_
var index = 0,_x000D_
inputIndex = 0;_x000D_
_x000D_
while (index < length){_x000D_
result[index++] = inputL[inputIndex];_x000D_
result[index++] = inputR[inputIndex];_x000D_
inputIndex++;_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
function floatTo16BitPCM(output, offset, input){_x000D_
for (var i = 0; i < input.length; i++, offset+=2){_x000D_
var s = Math.max(-1, Math.min(1, input[i]));_x000D_
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
}_x000D_
}_x000D_
_x000D_
function writeString(view, offset, string){_x000D_
for (var i = 0; i < string.length; i++){_x000D_
view.setUint8(offset + i, string.charCodeAt(i));_x000D_
}_x000D_
}_x000D_
_x000D_
function encodeWAV(samples){_x000D_
var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
var view = new DataView(buffer);_x000D_
_x000D_
/* RIFF identifier */_x000D_
writeString(view, 0, 'RIFF');_x000D_
/* file length */_x000D_
view.setUint32(4, 32 + samples.length * 2, true);_x000D_
/* RIFF type */_x000D_
writeString(view, 8, 'WAVE');_x000D_
/* format chunk identifier */_x000D_
writeString(view, 12, 'fmt ');_x000D_
/* format chunk length */_x000D_
view.setUint32(16, 16, true);_x000D_
/* sample format (raw) */_x000D_
view.setUint16(20, 1, true);_x000D_
/* channel count */_x000D_
view.setUint16(22, 2, true);_x000D_
/* sample rate */_x000D_
view.setUint32(24, sampleRate, true);_x000D_
/* byte rate (sample rate * block align) */_x000D_
view.setUint32(28, sampleRate * 4, true);_x000D_
/* block align (channel count * bytes per sample) */_x000D_
view.setUint16(32, 4, true);_x000D_
/* bits per sample */_x000D_
view.setUint16(34, 16, true);_x000D_
/* data chunk identifier */_x000D_
writeString(view, 36, 'data');_x000D_
/* data chunk length */_x000D_
view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
return view;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<audio controls autoplay></audio>_x000D_
<script type="text/javascript" src="recorder.js"> </script>_x000D_
<fieldset><legend>RECORD AUDIO</legend>_x000D_
<input onclick="startRecording()" type="button" value="start recording" />_x000D_
<input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
</fieldset>_x000D_
<script>_x000D_
var onFail = function(e) {_x000D_
console.log('Rejected!', e);_x000D_
};_x000D_
_x000D_
var onSuccess = function(s) {_x000D_
var context = new webkitAudioContext();_x000D_
var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
recorder = new Recorder(mediaStreamSource);_x000D_
recorder.record();_x000D_
_x000D_
// audio loopback_x000D_
// mediaStreamSource.connect(context.destination);_x000D_
}_x000D_
_x000D_
window.URL = window.URL || window.webkitURL;_x000D_
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
var recorder;_x000D_
var audio = document.querySelector('audio');_x000D_
_x000D_
function startRecording() {_x000D_
if (navigator.getUserMedia) {_x000D_
navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
} else {_x000D_
console.log('navigator.getUserMedia not present');_x000D_
}_x000D_
}_x000D_
_x000D_
function stopRecording() {_x000D_
recorder.stop();_x000D_
recorder.exportWAV(function(s) {_x000D_
_x000D_
audio.src = window.URL.createObjectURL(s);_x000D_
});_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
"If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you really want to run it. Say “yes” and then Build & Run again."
To add to that, this only holds true the moment you get the error, if you click OK, then tap on the app. It will do nothing. Scratched my head on that for 30 odd minutes, searching for alternative ways to address the problem.
Well the first option I could think of is that you could send a list
request with search parameters for your file, like title="File_1.xml" and fileExtension="xml"
. It will either return an empty list of files (there isn't one matching the serach criteria), or return a list with at least one file. If it's only one - it's easy. But if there are more - you'll have to select one of them based on some other fields. Remember that in gdrive you could have more than 1 file with the same name. So the more search parameters you provide, the better.
The export default {...}
construction is just a shortcut for something like this:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { foo(); bar() }
}
export default funcs
It must become obvious now that there are no foo
, bar
or baz
functions in the module's scope. But there is an object named funcs
(though in reality it has no name) that contains these functions as its properties and which will become the module's default export.
So, to fix your code, re-write it without using the shortcut and refer to foo
and bar
as properties of funcs
:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { funcs.foo(); funcs.bar() } // here is the fix
}
export default funcs
Another option is to use this
keyword to refer to funcs
object without having to declare it explicitly, as @pawel has pointed out.
Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:
function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }
export default {foo, bar, baz}
And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:
// util.js
export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }
export default {foo, bar, baz}
// a.js, using default export
import util from './util'
util.foo()
// b.js, using named exports
import {bar} from './util'
bar()
Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util'
to get all named exports in one object.
You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on uWSGI
.
No, there is no API for Google Voice announced as of 2021.
"pygooglevoice" can perform most of the voice functions from Python. It can send SMS. I've developed code to receive SMS messages, but the overhead is excessive given the current Google Voice interface. Each poll returns over 100K of content, so you'd use a quarter-gigabyte a day just polling every 30 seconds. There's a discussion on Google Code about this.
Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.
document.getElementById("ele_id").style.color="blue";
But, for changing multiple properies the more robust way is using Object.assign()
or, object spread operator {...}
;
const ele=document.getElementById("ele_id");
const custom_style={
display: "block",
color: "red"
}
//Object.assign():
Object.assign(ele.style,custum_style);
Spread operator works similarly, just the syntax is a little different.
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
With newer versions of moment.js you can also do this:
var dateTime = moment();
var dateValue = moment({
year: dateTime.year(),
month: dateTime.month(),
day: dateTime.date()
});
C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]
* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.
Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.
A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.
Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]
Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]
Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.
Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]
More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.
Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]
More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]
Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]
C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]
C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]
C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]
C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]
Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.
Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format
throughout all examples.
Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]
C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)
C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]
Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.
The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".
C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]
The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]
C++11/14/17/… References:
The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.
The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.
Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.
The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.
The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.
cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.
Note: Some information contained within these books may not be up-to-date or no longer considered best practice.
The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.
Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]
Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.
Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.
Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.
Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const
), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.
Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.
I would definitely suggest using element.getBoundingClientRect().
https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Summary
Returns a text rectangle object that encloses a group of text rectangles.
Syntax
var rectObject = object.getBoundingClientRect();
Returns
The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.
The returned value is a
TextRectangle
object, which contains read-onlyleft
,top
,right
andbottom
properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.
Here's a browser compatibility table taken from the linked MDN site:
+---------------+--------+-----------------+-------------------+-------+--------+
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0 | 3.0 (1.9) | 4.0 | (Yes) | 4.0 |
+---------------+--------+-----------------+-------------------+-------+--------+
It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/
You can use it like this:
var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();
console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);
Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).
Or here's another one using Chrome's console:
I have to mention that the width
and height
attributes of the getBoundingClientRect()
method's return value are undefined
in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width
, you could subtract the return value's right and left attributes, and for height
, you could subtract bottom and top attributes (like this).
Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
If you want to filter on Array of Objects then you can give
filter:({genres: 'Action', key :value }.
Individual property will be filtered by particular filter given for that property.
But if you wanted to something like filter by individual Property and filter globally for all properties then you can do something like this.
<tr ng-repeat="supp in $data | filter : filterObject | filter : search">
_x000D_
~Atul
For only horizontal lines
ax = plt.axes()
ax.yaxis.grid() # horizontal lines
This worked
If you just want to see how your picture will look on the website without uploading it to the server or without running your website on a local server, I think a very simple solution will be to convert your picture into a Base64 and add the contents into an IMG tag or as a background-image with CSS.
Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
Then, just assign a value to the variable outside this function like so:
player_wins = rps()
It will be assigned the return value (either True or False) of the function you just called.
After the comments, I decided to add that idiomatically, this would be better expressed thus:
def rps():
# Code to determine if player wins, assigning a boolean value (True or False)
# to the variable player_wins.
return player_wins
pw = rps()
This assigns the boolean value of player_wins
(inside the function) to the pw
variable outside the function.
Create one new class in your model and properties of LoginViewModel
and RegisterViewModel
:
public class UserDefinedModel()
{
property a1 as LoginViewModel
property a2 as RegisterViewModel
}
Then use UserDefinedModel
in your view.
You must have to define no-args or default constructor if you are creating your own constructor.
You can read why default or no argument constructor is required.
TO CHECK IF AN URL IS UP OR NOT
The code in your question can be rewritten as to a working version:
function send($packet=NULL, $url) {
// Do whatever you wanted to do with $packet
// The below two lines of code will let you know if https url is up or not
$command = 'curl -k '.$url;
return exec($command, $output, $retValue);
}
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:
public int countTrue(string data)
{
string[] splitdata = data.Split(',');
var results = from p in splitdata
where p.Contains("true")
select p;
return results.Count();
}
Your question is a a bit vague. This is a shell command that does what I think you want to do:
echo >> name_of_file
To define the preference in Fragment:
SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE);
editor.putString("credi_credito",cre);
editor.commit();
To call another activity or fragment the preference data:
SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE);
credit=pref.getString("credi_credito","");
if(credit.isNotEmpty)...
new Date().toLocaleTimeString()
My answer is inspired on my own working experience, and mostly in the book Two Scoops of Django which I highly recommend, and where you can find a more detailed explanation of everything. I just will answer some of the points, and any improvement or correction will be welcomed. But there also can be more correct manners to achieve the same purpose.
Projects
I have a main folder in my personal directory where I maintain all the projects where I am working on.
Source Files
I personally use the django project root as repository root of my projects. But in the book is recommended to separate both things. I think that this is a better approach, so I hope to start making the change progressively on my projects.
project_repository_folder/
.gitignore
Makefile
LICENSE.rst
docs/
README.rst
requirements.txt
project_folder/
manage.py
media/
app-1/
app-2/
...
app-n/
static/
templates/
project/
__init__.py
settings/
__init__.py
base.py
dev.py
local.py
test.py
production.py
ulrs.py
wsgi.py
Repository
Git or Mercurial seem to be the most popular version control systems among Django developers. And the most popular hosting services for backups GitHub and Bitbucket.
Virtual Environment
I use virtualenv and virtualenvwrapper. After installing the second one, you need to set up your working directory. Mine is on my /home/envs directory, as it is recommended on virtualenvwrapper installation guide. But I don't think the most important thing is where is it placed. The most important thing when working with virtual environments is keeping requirements.txt file up to date.
pip freeze -l > requirements.txt
Static Root
Project folder
Media Root
Project folder
README
Repository root
LICENSE
Repository root
Documents
Repository root. This python packages can help you making easier mantaining your documentation:
Sketches
Examples
Database
You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".
It won't install right out of the box... you need to create the installer class first.
Some reference on service installer:
How to: Add Installers to Your Service Application
Quite old... but this is what I am talking about:
Windows Services in C#: Adding the Installer (part 3)
By doing this, a ProjectInstaller.cs
will be automaticaly created. Then you can double click this, enter the designer, and configure the components:
serviceInstaller1
has the properties of the service itself: Description
, DisplayName
, ServiceName
and StartType
are the most important.
serviceProcessInstaller1
has this important property: Account
that is the account in which the service will run.
For example:
this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;
Your problem is in your use of the_field()
, which is for Advanced Custom Fields, a wordpress plugin.
If you want to use a field in a variable you have to use this: $web = get_field('website');
.
rdtsc solution did not work for me.
Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.
Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.
I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk
This fixed the issue for me.
If you want it to be CSS only, the disabling logic should be defined by CSS.
To move the logic in the CSS definitions, you'll have to use attribute selectors. Here are some examples :
=
You can choose to disable links that contain a specific href value like so :
<a href="//website.com/exact/path">Exact path</a>
[href="//website.com/exact/path"]{
pointer-events: none;
}
*=
Here, any link containing /keyword/
in path will be disabled
<a href="//website.com/keyword/in/path">Contains in path</a>
[href*="/keyword/"]{
pointer-events: none;
}
^=
the [attribute^=value]
operator target an attribute that starts with a specific value. Allows you to discard websites & root paths.
<a href="//website.com/begins/with/path">Begins with path</a>
[href^="//website.com/begins/with"]{
pointer-events: none;
}
You can even use it to disable non-https links. For example :
a:not([href^="https://"]){
pointer-events: none;
}
$=
The [attribute$=value]
operator target an attribute that ends with a specific value. It can be useful to discard file extensions.
<a href="/path/to/file.pdf">Link to pdf</a>
[href$=".pdf"]{
pointer-events: none;
}
Css can target any HTML attribute. Could be rel
, target
, data-custom
and so on...
<a href="#" target="_blank">Blank link</a>
[target=_blank]{
pointer-events: none;
}
You can chain multiple rules. Let's say that you want to disable every external link, but not those pointing to your website :
a[href*="//"]:not([href*="my-website.com"]) {
pointer-events: none;
}
Or disable links to pdf files of a specific website :
<a href="//website.com/path/to/file.jpg">Link to image</a>
[href^="//website.com"][href$=".jpg"] {
color: red;
}
Attributes selectors are supported since IE7. :not()
selector since IE9.
Just use Double.compare() method to compare double values.
Double.compare((d1,d2) == 0)
double d1 = 0.0;
double d2 = 0.0;
System.out.println(Double.compare((d1,d2) == 0)) // true
You can use the following solution to solve your problem:
echo date('H:i');
In my case on Ubuntu 16.04 server, and default tomcat installation it's under:
/var/lib/tomcat8
I think better answer is here because it allows you to get even cutout height too.
Take your root view, and add setOnApplyWindowInsetsListener (or you can override onApplyWindowInsets from it), and take insets.getSystemWindowInsets from it.
In my camera activity, i add padding equal to the systemWindowInsetBottom to my bottom layout. And finally, it fix cutout issue.
with appcompat it is like this
ViewCompat.setOnApplyWindowInsetsListener(mCameraSourcePreview, (v, insets) -> {
takePictureLayout.setPadding(0,0,0,insets.getSystemWindowInsetBottom());
return insets.consumeSystemWindowInsets();
});
without appcompat, this:
mCameraSourcePreview.setOnApplyWindowInsetsListener((v, insets) -> { ... })
Use <br/>
. For example:
Change log, upgrade version
Dependency | Old version | New version |
---------- | ----------- | -----------
Spring Boot | `1.3.5.RELEASE` | `1.4.3.RELEASE`
Gradle | `2.13` | `3.2.1`
Gradle plugin <br/>`com.gorylenko.gradle-git-properties` | `1.4.16` | `1.4.17`
`org.webjars:requirejs` | `2.2.0` | `2.3.2`
`org.webjars.npm:stompjs` | `2.3.3` | `2.3.3`
`org.webjars.bower:sockjs-client` | `1.1.0` | `1.1.1`
A very basic approach is alert(arrayObj.join('\n'))
, which will display each array element in a row.
As others have pointed out, you simply delimit them with a space.
However, knowing how the selectors work is also useful.
Consider this piece of HTML...
<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>
Using .a { ... }
as a selector will select the first and third. However, if you want to select one which has both a
and b
, you can use the selector .a.b { ... }
. Note that this won't work in IE6, it will simply select .b
(the last one).
You can set CSS using three different ways as mentioned below :-
1.External style sheet
2.Internal style sheet
3.Inline style
Preferred / ideal way of setting the css style is using as external style sheets when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file.
sample usage can be :-
<head>
<link rel="stylesheet" type="text/css" href="your_css_file_name.css">
</head>
If you want to apply a unique style to a single document then you can use Internal style sheet.
Don't use inline style sheet,as it mixes content with presentation and looses many advantages.
You could try an "onclick" event inside the LI tag, and change the "location.href" as in javascript.
You could also try placing the li tags within the a tags, however this is probably not valid HTML.
Both
gem query --local
and
ruby -S gem list --local
list 69 entries
While
ruby -e 'puts Gem::Specification.all_names'
gives me 82
I used wc -l
to get the numbers. Not sure if that is the right way to check. Tried to redirect the output to text files and diff'ed but that didn't help - will need to compare manually one by one.
i think there should be entry of your your_module.ko in /lib/modules/uname -r
/modules.dep and in /lib/modules/uname -r
/modules.dep.bin for "modprobe your_module" command to work
If you're trying to access the property of an object, you have to start with the scope of window
and go through each property of the object until you get to the one you want. Assuming that a.b.c
has been defined somewhere else in the script, you can use the following:
var values = window;
var str = 'a.b.c'.values.split('.');
for(var i=0; i < str.length; i++)
values = values[str[i]];
This will work for getting the property of any object, no matter how deep it is.
A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list)
x.count(x[0]) == len(x)
some simple benchmarks:
>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*5000', number=10000)
1.4383411407470703
>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*4999+[2]', number=10000)
1.4765670299530029
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*5000', number=10000)
0.26274609565734863
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*4999+[2]', number=10000)
0.25654196739196777
When i Tried your Code i got en Error when i wanted to fill the Array.
you can try to fill the Array like This.
Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray
Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
S2.Cells(k, "B") = VArray(k, 1) / 100
S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next
End Sub
import sqlite3
connection = sqlite3.connect("d:\\pythonAPI\\data.db")
cursor = connection.cursor()
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_table)
for clearer full path if you didn't get it clear
Straight after the $wpdb->insert()
that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Got this with flask :
Means that the port you're trying to bind to, is already in used by another service or process : got a hint on this in my code developed on Eclipse / windows :
if __name__ == "__main__":
# Check the System Type before to decide to bind
# If the system is a Linux machine -:)
if platform.system() == "Linux":
app.run(host='0.0.0.0',port=5000, debug=True)
# If the system is a windows /!\ Change /!\ the /!\ Port
elif platform.system() == "Windows":
app.run(host='0.0.0.0',port=50000, debug=True)
Your regular expression should look like:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/
Here is an explanation:
/^
(?=.*\d) // should contain at least one digit
(?=.*[a-z]) // should contain at least one lower case
(?=.*[A-Z]) // should contain at least one upper case
[a-zA-Z0-9]{8,} // should contain at least 8 from the mentioned characters
$/
^[^_]*_
will match all text up to the first underscore. Replace that with the empty string.
For example, in C#:
resultString = Regex.Replace(subjectString,
@"^ # Match start of string
[^_]* # Match 0 or more characters except underscore
_ # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
For learning regexes, take a look at http://www.regular-expressions.info
Use JSON.stringify()
and JSON.parse()
as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars
).
For devices with iOS 7.1 or later, you need to add:
yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;
In Angular 2 this is how we can set the default value for radio button:
HTML:
<label class="form-check-label">
<input type="radio" class="form-check-input" name="gender"
[(ngModel)]="gender" id="optionsRadios1" value="male">
Male
</label>
In the Component Class set the value of 'gender' variable equal to the value of radio button:
gender = 'male';
OS: Ubuntu 19.04
IntelliJ: 2019.1.2RC
I have read on all the previous answer and after some time trying to get this working I found that the IntelliJ Flutter plugin does not want the path to which flutter
instead it needs the base installation folder.
which flutter
output PATH_TO_FLUTTER/bin/flutter
you ONLY NEED the PATH_TO_FLUTTER
so remove everything from /bin...
Flutter SDK path
input and apply.That will then ask you to restart IntelliJ and you should get both Flutter and Dart configured:
Good luck!
The XMLHttpRequest.timeout
property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0
, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests
requests, used in a document environment or it will throw an InvalidAccessError
exception. You may not use a timeout for synchronous requests with an owning window.
IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.
More info can be found here.
Call this method on BaseActivity -> onCreate() and BaseFragment -> OnCreateView()
Tested on API 22, 23, 24, 25, 26, 27, 28, 29...uptodate version
fun Context.updateLang() {
val resources = resources
val config = Configuration(resources.configuration)
config.setLocale(PreferenceManager(this).getAppLanguage()) // language from preference
val dm = resources.displayMetrics
createConfigurationContext(config)
resources.updateConfiguration(config, dm)
}
Found an XML transform stylesheet here (wayback machine link, site itself is in german)
The stylesheet added here could be helpful:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.
The ALLOWED_HOSTS
list should contain fully qualified host names, not urls. Leave out the port and the protocol. If you are using 127.0.0.1
, I would add localhost
to the list too:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
You could also use *
to match any host:
ALLOWED_HOSTS = ['*']
Quoting the documentation:
Values in this list can be fully qualified names (e.g.
'www.example.com'
), in which case they will be matched against the request’sHost
header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard:'.example.com'
will matchexample.com
,www.example.com
, and any other subdomain ofexample.com
. A value of'*'
will match anything; in this case you are responsible to provide your own validation of theHost
header (perhaps in a middleware; if so this middleware must be listed first inMIDDLEWARE_CLASSES
).
Bold emphasis mine.
The status 400 response you get is due to a SuspiciousOperation
exception being raised when your host header doesn't match any values in that list.
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
I added below Path in environment variable
C:\Program Files\Java\jdk1.8.0_91\bin
and then compiled the program but got the error then I restarted the system and again compiled the program
This time it worked :)
Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
sqlitewraper.context, 0, intent,
PendingIntent.FLAG_NO_CREATE);
FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.
boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
System.out.print("k");
}
AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 1000 * 60, pendingIntent);
After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.
boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_UPDATE_CURRENT) != null);
if (alarmUp1) {
System.out.print("k");
}
When the repository package is different to @SpringBootApplication
/@EnableAutoConfiguration
, base package of @EnableJpaRepositories
is required to be defined explicitly.
Try to add @EnableJpaRepositories("com.pharmacy.persistence.users.dao")
to SpringBootRunner
As per Prakash K's answer Firefox does not support the innerText property. So you can simply test whether the user agent supports this property and proceed accordingly as below:
function changeText(elem, changeVal) {
if (typeof elem.textContent !== "undefined") {
elem.textContent = changeVal;
} else {
elem.innerText = changeVal;
}
}
in visualstudio 2008 you could use this code :
var _assembly = System.Reflection.Assembly
.GetExecutingAssembly().GetName().CodeBase;
var _path = System.IO.Path.GetDirectoryName(_assembly) ;
You can have a static field to store this kind of state. Or put it to the resource Bundle and restore from there on onCreate(Bundle savedInstanceState). Just make sure you entirely understand Android app managed lifecycle (e.g. why login() gets called on keyboard orientation change).
A little update to Evan Mulawski answer to make it shorter
List<string> allLinesText = File.ReadAllLines(fileName).ToList()
It can be done in the following two ways:
select floor(desired_field_value) from table
select round(desired_field_value-0.5) from table
The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.
You can use .bind()
or .live()
whichever is appropriate, but no need to name the function:
$('#target').bind('click hover', function () {
// common operation
});
or if you were doing this on lots of element (not much sense for an IE unless the element changes):
$('#target').live('click hover', function () {
// common operation
});
Note, this will only bind the first hover argument, the mouseover
event, it won't hook anything to the mouseleave
event.
I found that while adding
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
helps, sometimes it's a matter of your querying that determines how express handles it.
For instance, it could be that your parameters are passed in the URL rather than in the body
In such a case, you need to capture both the body and url parameters and use whichever is available (with preference for the body parameters in the case below)
app.route('/echo')
.all((req,res)=>{
let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
res.send(pars);
});
AWS sdk API will only best option for upload entire folder and repo to s3 and download entire bucket of s3 to locally.
For uploading whole folder to s3
aws s3 sync . s3://BucketName
for download whole s3 bucket locally
aws s3 sync s3://BucketName .
you can also assign path As like BucketName/Path for particular folder in s3 to download
In case of lubuntu 14.04 use
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
P.S-no need to restart the system.
You can actually sort it:
sorted(l,reverse=True)
l = [1, 2, 3]
sort=sorted(l,reverse=True)
print(sort)
You get:
[3,2,1]
But still if want to get the max do:
print(sort[0])
You get:
3
if second max:
print(sort[1])
and so on...
This would be better as a comment, sorry I do not have commenting permissions.
@mar10 comment was the missing piece I needed to do this.
Note that '/path/to/old/mercurial_repo' must be a path on the file system (not a URL), so you have to clone the original repository before. – mar10 Dec 27 '13 at 16:30
This comment was in regards to the answer that solved this for me, https://stackoverflow.com/a/10710294/2148757 which is the same answer as the one marked correct here, https://stackoverflow.com/a/16037861/2148757
This moved our hg project to git with the commit history intact.
To vertically center a span or div element within another div, add position relative to parent div and position absolute to the child div.Now the child div can be positioned anywhere inside the div.Example below centers both horizontally and vertically.
<div class="parent">
<div class="child">Vertically and horizontally centered child div</div>
</div>
css:
.parent{
position: relative;
}
.child{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
select substring(@string,charindex('@first',@string)+1,charindex('@second',@string)-(charindex('@first',@string)+1))
If its possible uninstall wamp then run installation as administrator then change you mysql.conf file like that
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
Allow from all
</Directory>
Not: Before I reinstall as admin the solution above didn't work for me
break;
is what you need to break out of any looping statement like for
, while
or do-while
.
In your case, its going to be like this:-
for(int x = 10; x < 20; x++) {
// The below condition can be present before or after your sysouts, depending on your needs.
if(x == 15){
break; // A unlabeled break is enough. You don't need a labeled break here.
}
System.out.print("value of x : " + x );
System.out.print("\n");
}
OK, here is a final solution based on ckramer's initial solution and palehorse's example that works in all of the browsers, including Opera. If you set history.navigationMode to 'compatible' then jQuery's ready function will fire on Back button operations in Opera as well as the other major browsers.
This page has more information.
Example:
history.navigationMode = 'compatible';
$(document).ready(function(){
alert('test');
});
I tested this in Opera 9.5, IE7, FF3 and Safari and it works in all of them.
The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.
The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:
Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.
If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.
Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.
Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.
So to sum up:
The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).
Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.
That's about it, price-vise the Quadros or FirePros are artificially overpriced.
At least you can use this:
document.addEventListener('click', musicPlay);
function musicPlay() {
document.getElementById('ID').play();
document.removeEventListener('click', musicPlay);
}
The music starts when the user clicks anywhere at the page.
It removes also instantly the EventListener, so if you use the audio controls the user can mute or pause it and the music doesn't start again when he clicks somewhere else..
This is my first ever post & I'm very inexperienced so please go easy on me, but I feel I've got a valid contribution that may be helpful to someone...
Sometimes you need a very big time window between repeat clicks (eg a mailto link where it takes a couple of secs for the email app to open and you don't want it re-triggered), yet you don't want to slow the user down elsewhere. My solution is to use class names for the links depending on event type, while retaining double-click functionality elsewhere...
var controlspeed = 0;
$(document).on('click','a',function (event) {
eventtype = this.className;
controlspeed ++;
if (eventtype == "eg-class01") {
speedlimit = 3000;
} else if (eventtype == "eg-class02") {
speedlimit = 500;
} else {
speedlimit = 0;
}
setTimeout(function() {
controlspeed = 0;
},speedlimit);
if (controlspeed > 1) {
event.preventDefault();
return;
} else {
(usual onclick code goes here)
}
});
Your MainActivity.java
is like this:
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);
You should to first get your image from Resource as Bitmap
or Drawable
.
If get as Bitmap
:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);
Or if get as Drawable
:
Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);
Then create new file as Newreza.java
near MainActivity.java
, and copy bottom codes in Newreza.java
:
package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:[email protected]
public class Newreza{
int a,x,y;
float bmr;
public Bitmap setEffect(Bitmap bm,float radius,int color){
bm=bm.copy(Bitmap.Config.ARGB_8888,true);
bmr=radius*bm.getWidth();
for(y=0;y<bmr;y++){
a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
for(x=0;x<a;x++){
bm.setPixel(x,y,color);
}
}
for(y=0;y<bmr;y++){
a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
for(x=a;x<bm.getWidth();x++){
bm.setPixel(x,y,color);
}
}
for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
for(x=a;x<bm.getWidth();x++){
bm.setPixel(x,y,color);
}
}
for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
for(x=0;x<a;x++){
bm.setPixel(x,y,color);
}
}
return bm;
}
public Drawable setEffect(Drawable d,float radius,int color){
return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
}
}
Just notice that replace your package name with first line in the code.
It %100 works, because is written in details :)
The following code works to prevent column breaks inside elements:
-webkit-column-break-inside: avoid;
-moz-column-break-inside: avoid;
-o-column-break-inside: avoid;
-ms-column-break-inside: avoid;
column-break-inside: avoid;
You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):
:10,20 s/^/#
with 10 and 20 being the start and end line numbers of the lines you want to comment out
and to undo when you are complete:
:10,20 s/^#//
If the required properties need to set in system then there is no option than -D But if you need those properties while bootstrapping an application then loading properties through the properties files is a best option. It will not require to change build for a single property.
use Firebase.getAuth()
. It returns the current state of the Firebase client. Otherwise the return value is null
Here are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html
You can use "translateX"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
Short answer - no.
You will only be charged for the time that your instance is up and running, in hour increments. If you are using other services in conjunction you may be charged for those but it would be separate from your server instance.
Environment variable (can access anywhere/ dynamic object) is a type of variable. They are of 2 types system environment variables and user environment variables.
System variables having a predefined type and structure. That are used for system function. Values that produced by the system are stored in the system variable. They generally indicated by using capital letters Example: HOME,PATH,USER
User environment variables are the variables that determined by the user,and are represented by using small letters.
x*x
or x*x*x
will be faster than pow
, since pow
must deal with the general case, whereas x*x
is specific. Also, you can elide the function call and suchlike.
However, if you find yourself micro-optimizing like this, you need to get a profiler and do some serious profiling. The overwhelming probability is that you would never notice any difference between the two.
I know this is an old post but this solved my problem.
@font-face{_x000D_
font-family: "Font Name";_x000D_
src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
notice src:url("../fonts/font-name.ttf");
we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.
hope this helps someone down the line:) happy coding
You can use following snippet to check Internet Connection.
It will useful both way that you can check which Type of NETWORK Connection is available so you can do your process on that way.
You just have to copy following class and paste directly in your package.
/**
* @author Pratik Butani
*/
public class InternetConnection {
/**
* CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
*/
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
// connected to the mobile provider's data plan
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
}
Now you can use like:
if (InternetConnection.checkConnection(context)) {
// Its Available...
} else {
// Not Available...
}
DON'T FORGET to TAKE Permission :) :)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
You can modify based on your requirement.
Thank you.
Numpy can do it:
>>> import numpy
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]
If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:
SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
FROM (
SELECT name, COUNT(*) AS Rcount, 0 AS Acount
FROM Results GROUP BY name
UNION ALL
SELECT name, 0, count(*)
FROM Archive_Results
GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;
String
is immutable for several reasons, here is a summary:
String
in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.String
is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).That being said, immutability of String
only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.
In your example, if String
was mutable, then consider the following example:
String a="stack";
System.out.println(a);//prints stack
a.setValue("overflow");
System.out.println(a);//if mutable it would print overflow
Properties that are database specific are:
hibernate.connection.driver_class
: JDBC driver classhibernate.connection.url
: JDBC URLhibernate.connection.username
: database userhibernate.connection.password
: database passwordhibernate.dialect
: The class name of a Hibernate org.hibernate.dialect.Dialect
which allows Hibernate to generate SQL optimized for a particular relational database. To change the database, you must:
Dialect
used by Hibernate to talk to the databaseThere are two drivers to connect to SQL Server; the open source jTDS and the Microsoft one. The driver class and the JDBC URL depend on which one you use.
The driver class name is net.sourceforge.jtds.jdbc.Driver
.
The URL format for sqlserver is:
jdbc:jtds:sqlserver://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So the Hibernate configuration would look like (note that you can skip the hibernate.
prefix in the properties):
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://<server>[:<port>][/<database>]</property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
The driver class name is com.microsoft.sqlserver.jdbc.SQLServerDriver
.
The URL format is:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
So the Hibernate configuration would look like:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://[serverName[\instanceName][:portNumber]];databaseName=<databaseName></property>
<property name="connection.username">sa</property>
<property name="connection.password">lal</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
...
</session-factory>
</hibernate-configuration>
Add \t
for tab and \n
for new line.
It's undefined; doing things like Jon Skeet suggested will get you an approximation on a given platform, but the way to know precisely for a specific platform is to use a profiler.
No fancy tricks needed:
for i in *.java; do
[ -f "$i" ] || break
...
done
The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java
. In bash
(or shells supporting something similar), you can use the nullglob
option
to simply ignore a failed match and not enter the body of the loop.
shopt -s nullglob
for i in *.java; do
...
done
Usage and Lingo:
Real World Example:
Hash & Co., founded in 1803 and lacking any computer technology had a total of 300 filing cabinets to keep the detailed information (the records) for their approximately 30,000 clients. Each file folder were clearly identified with its client number, a unique number from 0 to 29,999.
The filing clerks of that time had to quickly fetch and store client records for the working staff. The staff had decided that it would be more efficient to use a hashing methodology to store and retrieve their records.
To file a client record, filing clerks would use the unique client number written on the folder. Using this client number, they would modulate the hash key by 300 in order to identify the filing cabinet it is contained in. When they opened the filing cabinet they would discover that it contained many folders ordered by client number. After identifying the correct location, they would simply slip it in.
To retrieve a client record, filing clerks would be given a client number on a slip of paper. Using this unique client number (the hash key), they would modulate it by 300 in order to determine which filing cabinet had the clients folder. When they opened the filing cabinet they would discover that it contained many folders ordered by client number. Searching through the records they would quickly find the client folder and retrieve it.
In our real-world example, our buckets are filing cabinets and our records are file folders.
An important thing to remember is that computers (and their algorithms) deal with numbers better than with strings. So accessing a large array using an index is significantly much faster than accessing sequentially.
As Simon has mentioned which I believe to be very important is that the hashing part is to transform a large space (of arbitrary length, usually strings, etc) and mapping it to a small space (of known size, usually numbers) for indexing. This if very important to remember!
So in the example above, the 30,000 possible clients or so are mapped to a smaller space.
The main idea in this is to divide your entire data set into segments as to speed up the actual searching which is usually time consuming. In our example above, each of the 300 filing cabinet would (statistically) contain about 100 records. Searching (regardless the order) through 100 records is much faster than having to deal with 30,000.
You may have noticed that some actually already do this. But instead of devising a hashing methodology to generate a hash key, they will in most cases simply use the first letter of the last name. So if you have 26 filing cabinets each containing a letter from A to Z, you in theory have just segmented your data and enhanced the filing and retrieval process.
Hope this helps,
Jeach!
Per the official guide, use of
pylab
is no longer recommended.matplotlib.pyplot
should be used directly instead.
Globally setting font sizes via rcParams
should be done with
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
The defaults can be restored using
plt.rcParams.update(plt.rcParamsDefault)
You can also do this by creating a style sheet in the stylelib
directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()
). The style sheet format is
axes.labelsize: 16
axes.titlesize: 16
If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle
then you can use it via
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
You can also create (or modify) a matplotlibrc file which shares the format
axes.labelsize = 16
axes.titlesize = 16
Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.
A complete list of the rcParams
keys can be retrieved via plt.rcParams.keys()
, but for adjusting font sizes you have (italics quoted from here)
axes.labelsize
- Fontsize of the x and y labelsaxes.titlesize
- Fontsize of the axes titlefigure.titlesize
- Size of the figure title (Figure.suptitle()
)xtick.labelsize
- Fontsize of the tick labelsytick.labelsize
- Fontsize of the tick labelslegend.fontsize
- Fontsize for legends (plt.legend()
, fig.legend()
)legend.title_fontsize
- Fontsize for legend titles, None
sets to the same as the default axes. See this answer for usage example.all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}
or a float
in pt
. The string sizes are defined relative to the default font size which is specified by
font.size
- the default font size for text, given in pts. 10 pt is the standard valueAdditionally, the weight can be specified (though only for the default it appears) by
font.weight
- The default weight of the font used by text.Text
. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900}
or 'normal'
(400), 'bold'
(700), 'lighter'
, and 'bolder'
(relative with respect to current weight).Use following meta tag in your html header file, This works for me.
<meta http-equiv="Pragma" content="no-cache">
Use a timer. There are 3 basic kinds, each suited for different purposes.
Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.
When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.
This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.
For most cases, I recommend System.Timers.Timer.
This ought to work:
^\d+\s?(\([^\)]+\)\s?)?Z$
Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:
First the beginning:
^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace
Then this part:
(\([^\)]+\)\s?)?
Is actually:
(.............)?
Which makes the following contents optional, only if it exists fully
\([^\)]+\)\s?
\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace
And the end is made up of
Z$
Where
Z = your constant string
$ = the end of the string
I think the easiest would be something like:
// Joda Time
DateTime dateTime=new DateTime();
StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();
These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.
I find the -e
flag elegant and straight forward
bash$ STR="Hello\nWorld"
bash$ echo -e $STR
Hello
World
If the string is the output of another command, I just use quotes
indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"
SHOULD be unique does not mean MUST be unique. However, as stated, some parsers would fail and others would just use the last value parsed. However, if the spec was cleaned up a little to allow for duplicates then I could see a use where you may have an event handler which is transforming the JSON to HTML or some other format... In such cases it would be perfectly valid to parse the JSON and create another document format...
[
"div":
{
"p": "hello",
"p": "universe"
},
"div":
{
"h1": "Heading 1",
"p": "another paragraph"
}
]
could then easily parse to html for example:
<body>
<div>
<p>hello</p>
<p>universe</p>
</div>
<div>
<h1>Heading 1</h1>
<p>another paragraph</p>
</div>
</body>
I can see the reasoning behind the question but as it stands... I wouldn't trust it.
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
You want to use two keys independently, so you have two choices:
Store the data redundantly with two dicts as {'banana' : {'blue' : 4, ...}, .... }
and {'blue': {'banana':4, ...} ...}
. Then, searching and sorting is easy but you have to make sure you modify the dicts together.
Store it just one dict, and then write functions that iterate over them eg.:
d = {'banana' : {'blue' : 4, 'yellow':6}, 'apple':{'red':1} }
blueFruit = [(fruit,d[fruit]['blue']) if d[fruit].has_key('blue') for fruit in d.keys()]
Adam, following your comment above ("I wanted the empty plot to serve as filler in a multiplot (mfrow) plot."), what you actually want is the mfg option
par(mfg=c(row,column))
- which controls where you want to put the next plot. For instance, to put a plot in the middle of a 3x3 multiplot, do
par(mfrow=c(3,3))
par(mfg=c(2,2))
plot(rnorm(10))
Ref: The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
Out: The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.
public class Example
{
public static void Main()
{
int val1 = 0; //must be initialized
int val2; //optional
Example1(ref val1);
Console.WriteLine(val1);
Example2(out val2);
Console.WriteLine(val2);
}
static void Example1(ref int value)
{
value = 1;
}
static void Example2(out int value)
{
value = 2;
}
}
/* Output 1 2
Ref and out in method overloading
Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out).
A list can be sorted and deduplicated using built-in functions:
myList = sorted(set(myList))
In openCV whenever you try to display an oversized image or image bigger than your display resolution you get the cropped display. It's a default behaviour.
In order to view the image in the window of your choice openCV encourages to use named window. Please refer to namedWindow documentation
The function namedWindow creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
cv.namedWindow(name, flags=CV_WINDOW_AUTOSIZE)
where each window is related to image container by the name arg, make sure to use same name
eg:
import cv2
frame = cv2.imread('1.jpg')
cv2.namedWindow("Display 1")
cv2.resizeWindow("Display 1", 300, 300)
cv2.imshow("Display 1", frame)
If you have a FILE *
, you can use functions like fscanf
, fprintf
and fgets
etc. If you have just the file descriptor, you have limited (but likely faster) input and output routines read
, write
etc.
>>> def func(a, *args, **kwargs):
... print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
...
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}
>>> def anotherfunct(beta, *args):
... print 'beta %s, args %s' % (beta, args)
...
>>> def func(a, *args, **kwargs):
... anotherfunct(a, *args)
...
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>>
Like Playnox's solution, but with the elegant built-in DirectoryIterator:
function delete_directory($dirPath){
if(is_dir($dirPath)){
$objects=new DirectoryIterator($dirPath);
foreach ($objects as $object){
if(!$object->isDot()){
if($object->isDir()){
delete_directory($object->getPathname());
}else{
unlink($object->getPathname());
}
}
}
rmdir($dirPath);
}else{
throw new Exception(__FUNCTION__.'(dirPath): dirPath is not a directory!');
}
}
You can also use this (based on a few of the above answers):
file = open('filename.txt', 'w')
file.close()
of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.
happy coding!
Normally virtualenv
creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32
for some reason, I would use a different directory for environments.
You shouldn't need to mess with paths: use the activate
script (in <env>\Scripts
) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate
to set everything back to how it was before activation.
Example:
c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>
Notice how I didn't need to specify a path for deactivate
- activate
does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix
and it should print the root of your environment.)
You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate
so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.
If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper
(the link points to a port of this to Powershell) makes life with virtualenv
even easier.
Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv
. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.
Further update: You should be able to use pip
, distribute
instead of setuptools
, and just plain python setup.py install
with virtualenv
. Just ensure you've activated an environment before installing something into it.
http://callmenick.com/2014/02/18/create-an-animated-resizing-header-on-scroll/
This link has a great tutorial with source code that you can play with, showing how to make elements within the header smaller as well as the header itself.
Use PHP_EOL
which outputs \r\n
or \n
depending on the OS.
I assume you want lowercase the text. Solution is pretty simple:
ggVGu
Explanation:
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
Try to set another MIME-type:
exportData = 'data:application/octet-stream;charset=utf-8,';
But there are can be problems with file name in save dialog.
This will show the 3rd max salary from table employee.
If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6
and so on...
select min(sal) from(select distinct(sal) from emp where rownum<=3 order by sal desc);
Dim rg As Range
Set rg = Range("A1:E10")
Dim i As Integer
For i = 1 To rg.Rows.Count
For j = 1 To rg.Columns.Count
rg.Cells(i, j).Value = rg.Cells(i, j).Address(False, False)
Next
Next
Update September 26, 2016:
As @Taytay's answer says, instead of the 'typings' installations that we used a few months ago, we can now use:
npm install --save @types/lodash
Here are some additional references supporting that answer:
If still using the typings installation, see the comments below (by others) regarding '''--ambient''' and '''--global'''.
Also, in the new Quick Start, config is no longer in index.html; it's now in systemjs.config.ts (if using SystemJS).
Original Answer:
This worked on my mac (after installing Angular 2 as per Quick Start):
sudo npm install typings --global
npm install lodash --save
typings install lodash --ambient --save
You will find various files affected, e.g.
Angular 2 Quickstart uses System.js, so I added 'map' to the config in index.html as follows:
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
map: {
lodash: 'node_modules/lodash/lodash.js'
}
});
Then in my .ts code I was able to do:
import _ from 'lodash';
console.log('lodash version:', _.VERSION);
Edits from mid-2016:
As @tibbus mentions, in some contexts, you need:
import * as _ from 'lodash';
If starting from angular2-seed, and if you don't want to import every time, you can skip the map and import steps and just uncomment the lodash line in tools/config/project.config.ts.
To get my tests working with lodash, I also had to add a line to the files array in karma.conf.js:
'node_modules/lodash/lodash.js',
There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.
For functions with return types, there is Func<> and for functions without return types there is Action<>.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
// Java 8
int vInt = Integer.parseUnsignedInt("4294967295");
System.out.println(vInt); // -1
String sInt = Integer.toUnsignedString(vInt);
System.out.println(sInt); // 4294967295
long vLong = Long.parseUnsignedLong("18446744073709551615");
System.out.println(vLong); // -1
String sLong = Long.toUnsignedString(vLong);
System.out.println(sLong); // 18446744073709551615
// Guava 18.0
int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
System.out.println(vIntGu); // -1
String sIntGu = UnsignedInts.toString(vIntGu);
System.out.println(sIntGu); // 4294967295
long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
System.out.println(vLongGu); // -1
String sLongGu = UnsignedLongs.toString(vLongGu);
System.out.println(sLongGu); // 18446744073709551615
/**
Integer - Max range
Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1
Long - Max range
Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
*/
please refer to this post for the changes in ruby1.9 Getting an ASCII character code in Ruby using `?` (question mark) fails
The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.
Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!
Google should probably have a caveat saying you may also need JRE OR JDK
There is another solution by lord.garbage to run GUI apps in a container without using VNC, SSH and X11 forwarding. It is mentioned here too.
Personally multer didn't work for me after weeks trying to get this file upload thing right. Then I switch to formidable and after a few days I got it working perfectly without any error, multiple files, express and react.js even though react is optional. Here's the guide: https://www.youtube.com/watch?v=jtCfvuMRsxE&t=122s
This is working Oracle example but it should work in MySQL too.
You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.
SELECT empno, ename, job
FROM scott.emp
WHERE (CASE WHEN job = 'MANAGER' THEN '1'
WHEN job = 'CLERK' THEN '2'
ELSE '0' END) IN (1, 2)
Please change only the name of the function; no other change is required
<script>
function totalbandwidthresult() {
alert("fdf");
var fps = Number(document.calculator.fps.value);
var bitrate = Number(document.calculator.bitrate.value);
var numberofcameras = Number(document.calculator.numberofcameras.value);
var encoding = document.calculator.encoding.value;
if (encoding = "mjpeg") {
storage = bitrate * fps;
} else {
storage = bitrate;
}
totalbandwidth = (numberofcameras * storage) / 1000;
alert(totalbandwidth);
document.calculator.totalbandwidthresult.value = totalbandwidth;
}
</script>
<form name="calculator" class="formtable">
<div class="formrow">
<label for="rcname">RC Name</label>
<input type="text" name="rcname">
</div>
<div class="formrow">
<label for="fps">FPS</label>
<input type="text" name="fps">
</div>
<div class="formrow">
<label for="bitrate">Bitrate</label>
<input type="text" name="bitrate">
</div>
<div class="formrow">
<label for="numberofcameras">Number of Cameras</label>
<input type="text" name="numberofcameras">
</div>
<div class="formrow">
<label for="encoding">Encoding</label>
<select name="encoding" id="encodingoptions">
<option value="h264">H.264</option>
<option value="mjpeg">MJPEG</option>
<option value="mpeg4">MPEG4</option>
</select>
</div>Total Storage:
<input type="text" name="totalstorage">Total Bandwidth:
<input type="text" name="totalbandwidth">
<input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>
You want to use "multiline".
$string =~ /(START)(.+?)(END)/m;
You are using older MySql version. Update your myqsl to 5.6.5+ it will work.
The best way I've found is to run this command from terminal
sudo pip install [package_name] --upgrade
sudo
will ask to enter your root password to confirm the action.
Note: Some users may have pip3 installed instead. In that case, use
sudo pip3 install [package_name] --upgrade
Here is what I did, hope it is helpful to anyone else :
Steps:
/etc/rc.d/rc.mongod stop
, if you use something else, like systemd you should check your documentation how to do thatmkdir /mnt/database
chown mongodb:mongodb -R /mnt/database/mongodb
) - thanks @DanailGabenski.cp -R /var/lib/mongodb/ /mnt/database/
rm -rf /var/lib/mongodb/
ln -s /mnt/database/mongodb /var/lib/mongodb
/etc/rc.d/rc.mongod start
mongo
to connect to your database to see if everything is all right )There is no need to tell that you should be careful when you do this, especialy with rm -rf
but I think this is the best way to do it.
You should never try to copy database dir while mongod is running, because there might be services that write / read from it which will change the content of your database.
Try mydatagrid.Items.Refresh()
How about this for a clear
- os.system('cls')
That is about as short as could be!
Here is a JavaScript implementation of the Y-Combinator and the Factorial function (from Douglas Crockford's article, available at: http://javascript.crockford.com/little.html).
function Y(le) {
return (function (f) {
return f(f);
}(function (f) {
return le(function (x) {
return f(f)(x);
});
}));
}
var factorial = Y(function (fac) {
return function (n) {
return n <= 2 ? n : n * fac(n - 1);
};
});
var number120 = factorial(5);
I ended up having to make a slight change using the click event on the input element by also setting the checked prop after firing the click event.
$(y.Ctrl).multiselect("widget").find(":checkbox").each(function () {
if ($.inArray(this.value, uniqueVals) != -1) {
$(this).click();
$(this).prop('checked', true);
}
});
I found this is working perfectly
str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))
pip search
command does not show installed packages, but search packages in pypi.
Use pip freeze
command and grep
to see installed packages:
pip freeze | grep Django
If you want to compare text String or the text will change dynamically then you can created a view in Constraint layout it will adjust according to text length like this
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txt_Previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Last Month Rankings"
android:textColor="@color/colorBlue"
android:textSize="15sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<View
android:layout_width="0dp"
android:layout_height="0.7dp"
android:background="@color/colorBlue"
app:layout_constraintEnd_toEndOf="@+id/txt_Previous"
app:layout_constraintStart_toStartOf="@+id/txt_Previous"
app:layout_constraintBottom_toBottomOf="@id/txt_Previous"/>
</android.support.constraint.ConstraintLayout>
The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:
Digest Password Support
The WSS 1.1 Username Token Profile allows digest passwords to be sent in a
wsse:UsernameToken
of a SOAP message. Two more optional elements are included in thewsse:UsernameToken
in this case:wsse:Nonce
andwsse:Created
. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )
This is how a UsernameToken with Digest Password looks like:
<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c"> <wsse:Username>Alice</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce> <wsu:Created>2008-04-28T10:02:11Z</wsu:Created> </wsse:UsernameToken>
Here is an example using shell (bash
):
#!/bin/bash
# loop & print a folder recusively,
print_folder_recurse() {
for i in "$1"/*;do
if [ -d "$i" ];then
echo "dir: $i"
print_folder_recurse "$i"
elif [ -f "$i" ]; then
echo "file: $i"
fi
done
}
# try get path from param
path=""
if [ -d "$1" ]; then
path=$1;
else
path="/tmp"
fi
echo "base path: $path"
print_folder_recurse $path
If it is a console application, use Ctrl + F5.
The push
command has a -n
/--dry-run
option which will compute what needs to be pushed but not actually do it. Does that work for you?
I had this problem today, and all one-liners here failed to me because the files contained spaces in the names.
This is what I came up with that worked:
grep -ril <WORD1> | sed 's/.*/"&"/' | xargs grep -il <WORD2>
Make sure you didn't by mistake changed the file type of __init__.py
files. If, for example, you changed their type to "Text" (instead of "Python"), PyCharm won't analyze the file for Python code. In that case, you may notice that the file icon for __init__.py
files is different from other Python files.
To fix, in Settings > Editor > File Types
, in the "Recognized File Types" list click on "Text" and in the "File name patterns" list remove __init__.py
.
yup.. here's my code:
<style>
.circle{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: blue
}
</style>
<div class="circle">
</div>
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
@Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
You can try this
public string ToString(this object value)
{
// this will throw an exception if value is null
string val = Convert.ToString (value);
// it can be a space
If (string.IsNullOrEmpty(val.Trim())
return string.Empty:
}
// to avoid not all code paths return a value
return val;
}
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
For some reason, converting to a 2 dimensional array didn't work for me. But the following approach did:
public void SetRow(Range range, string[] data)
{
range.get_Resize(1, data.Length).Value2 = data;
}
Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80
(there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80
. Make sure that View ? Word Wrap
is selected.
To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User
and use any of the following rules:
{
// set vertical rulers in specified columns.
// Use "rulers": [80] for just one ruler
// default value is []
"rulers": [80, 100, 120],
// turn on word wrap for source and text
// default value is "auto", which means off for source and on for text
"word_wrap": true,
// set word wrapping at this column
// default value is 0, meaning wrapping occurs at window width
"wrap_width": 80
}
These settings can also be used in a .sublime-project
file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings
file if you only want them to apply to files written in a certain language (Python.sublime-settings
vs. JavaScript.sublime-settings
, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User
.
As always, if you have multiple entries in your settings file, separate them with commas ,
except for after the last one. The entire content should be enclosed in curly braces { }
. Basically, make sure it's valid JSON.
If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.
Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0
and O
(digit zero and capital letter oh) and 1
and l
(digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).
As Jonathan Leaders mentioned here, it is important to run the command/script elevated to be able to change environment variables for 'machine', but running some commands elevated doesn't have to be done with the Community Extensions, so I'd like to modify and extend JeanT's answer in a way, that changing machine variables also can be performed even if the script itself isn't run elevated:
function Set-Path ([string]$newPath, [bool]$permanent=$false, [bool]$forMachine=$false )
{
$Env:Path += ";$newPath"
$scope = if ($forMachine) { 'Machine' } else { 'User' }
if ($permanent)
{
$command = "[Environment]::SetEnvironmentVariable('PATH', $env:Path, $scope)"
Start-Process -FilePath powershell.exe -ArgumentList "-noprofile -command $Command" -Verb runas
}
}
If you have installed x-pack to secure elasticseach, the request should contains the valid credential details.
curl -XGET -u "elastic:passwordForElasticUser" 'localhost:9200'
Infact, if the security enabled all the subsequent requests should follow the same pattern (inline credentials should be provided).
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");
this work if you move to previous or next field by mouse, but by enter key, this is not work !!!
You can use python garbage collector:
import gc
gc.collect()
if you want to create new instance without set initial value when instance
1- you have to use class not interface
2- you have to set initial value when create class
export class IStudentDTO {
Id: number = 0;
Name: string = '';
student: IStudentDTO = new IStudentDTO();
We have a weekly sql dump into a subversion repo. It's fully automated but it's a REALLY beefy task.
You'll want to limit the number of revisions because it really chows disk space after a while!
The shortcut key is ctrl+] to indentation and ctrl +[ to unindent
There is a simplified solution from bootstrap here (where you don't need to create a new class): http://getbootstrap.com/examples/sticky-footer-navbar/
When you open that page, right click on a browser and "View Source" and open the sticky-footer-navbar.css file (http://getbootstrap.com/examples/sticky-footer-navbar/sticky-footer-navbar.css)
you can see that you only need this CSS
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
background-color: #f5f5f5;
}
for this HTML
<html>
...
<body>
<!-- Begin page content -->
<div class="container">
</div>
...
<footer class="footer">
</footer>
</body>
</html>
Try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
String currentData = sdf.format(new Date());
Toast.makeText(getApplicationContext(), ""+currentData,Toast.LENGTH_SHORT ).show();
Previous answers were good and correct, but in my opinion, an extra names
parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers
.
usecols
and names
parametersdf = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])
or use header=None
to explicitly tells people that the csv
has no headers (anyway both lines are identical)
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)
So that you can retrieve your data by
# with `names` parameter
df['colA']
df['colB']
instead of
# without `names` parameter
df[0]
df[1]
Based on read_csv, when names
are passed explicitly, then header
will be behaving like None
instead of 0
, so one can skip header=None
when names
exist.
I stumbled over the same question and I've found a solution.
First make sure you upgrade to LESS 1.6 at least.
You can use npm
for that case.
Now you can use the following mixin:
.if (@condition, @property, @value) when (@condition = true){
@{property}: @value;
}
Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:
.myHeadline {
.if(@include-lineHeight, line-height, '35px');
}
If @include-lineheight resolves to true LESS will print the line-height: 35px
and it will skip the mixin if @include-lineheight is not true.
In Xcode, check the "Requires Full Screen" checkbox under General > Targets, as shown below.
var x = $('#h_v').val();
alert(x);
There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).
The concrete code is by Michal Migurski and by Matt Knapp:
/(["\']).*?(?<!\\)(\\\\)*\1/is
should work with any quoted string
You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project
I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.
You do
for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
t.join()
After this for loop, you can be sure all threads have finished their jobs.
You will want to use interfaces. Generally, multiple inheritance is bad because of the Diamond Problem:
abstract class A {
abstract string foo();
}
class B extends A {
string foo () { return "bar"; }
}
class C extends A {
string foo() {return "baz"; }
}
class D extends B, C {
string foo() { return super.foo(); } //What do I do? Which method should I call?
}
C++ and others have a couple ways to solve this, eg
string foo() { return B::foo(); }
but Java only uses interfaces.
The Java Trails have a great introduction on interfaces: http://download.oracle.com/javase/tutorial/java/concepts/interface.html You'll probably want to follow that before diving into the nuances in the Android API.
If you really want something like goto statements, you could always try breaking to named blocks.
You have to be within the scope of the block to break to the label:
namedBlock: {
if (j==2) {
// this will take you to the label above
break namedBlock;
}
}
I won't lecture you on why you should avoid goto's - I'm assuming you already know the answer to that.
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
#include <stdio.h>
main()
{
char str[100];
int num;
while(1) {
printf("Enter a number: ");
scanf("%[^0-9]%d",str,&num);
printf("You entered the number %d\n",num);
}
return 0;
}
%[^0-9]
in scanf()
gobbles up all that is not between 0
and 9
. Basically it cleans the input stream of non-digits and puts it in str
. Well, the length of non-digit sequence is limited to 100. The following %d
selects only integers in the input stream and places it in num
.
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
As @COLDSPEED so eloquently pointed out the error explicitly tells you to install xlrd.
pip install xlrd
And you will be good to go.
An Observable is an object that emits a stream of events: Next, Error and Completed.
When your function returns an Observable, it is not returning a stream, but an instance of Observable. The flatMap
operator simply maps that instance to a stream.
That is the behaviour of flatMap
when compared to map
: Execute the given function and flatten the resulting object into a stream.
Preferred string type in C++ is string
, defined in namespace std
, in header <string>
and you can initialize it like this for example:
#include <string>
int main()
{
std::string str1("Some text");
std::string str2 = "Some text";
}
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.
The Code:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MealNinja"
mc:Ignorable="d"
Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
<Window.Effect>
<DropShadowEffect Opacity="0.5"/>
</Window.Effect>
<Grid Background="#FF423C3C">
<TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
<TabControl.Resources>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
<ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
</Border>
<Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
<Setter TargetName="ContentSite" Property="Width" Value="30" />
<Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<ContentPresenter Content="{TemplateBinding Content}">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="#FF6E6C67" />
<Setter Property="Height" Value="90" />
<Setter Property="Margin" Value="0" />
<Setter Property="Padding" Value="0" />
<Setter Property="FontFamily" Value="DokChampa" />
<Setter Property="FontSize" Value="16" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="UseLayoutRounding" Value="False" />
</Style>
<Style x:Key="tabGrids">
<Setter Property="Grid.Background" Value="#FFE5E5E5" />
<Setter Property="Grid.Margin" Value="6,10,10,10" />
</Style>
</TabControl.Resources>
<TabItem Header="Planner">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section 2">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section III">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Section 04">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
<TabItem Header="Tools">
<Grid Style="{StaticResource tabGrids}"/>
</TabItem>
</TabControl>
</Grid>
</Window>
Screenshot:
This is known as a fork bomb. It keeps splitting itself until there is no option but to restart the system. http://en.wikipedia.org/wiki/Fork_bomb
Well all the answers above/below are producing a warning about no entry point in storyboard.
If you want to have 2 (or more) entry view controllers that depend on some condition (say conditionVariable) then what you should do is:
Use next code:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = window!.rootViewController! as! UINavigationController
navigationController.performSegueWithIdentifier(conditionVariable ? "id1" : "id2")
return true
}
Hope this helps.
As per my knowledge both type of fetch depends your requirement.
FetchType.LAZY
is on demand (i.e. when we required the data).
FetchType.EAGER
is immediate (i.e. before our requirement comes we are unnecessarily fetching the record)
Try this out. Hope this helps
<div id="single" dir="rtl">
<div class="common">Single</div>
</div>
<div id="both" dir="ltr">
<div class="common">Both</div>
</div>
#single, #both{
width: 100px;
height: 100px;
overflow: auto;
margin: 0 auto;
border: 1px solid gray;
}
.common{
height: 150px;
width: 150px;
}
<form>
syn<input type="checkbox" name="checkfield" id="g01-01" />
</form>
js:
$('#g01-01').on('change',function(){
var _val = $(this).is(':checked') ? 'checked' : 'unchecked';
alert(_val);
});
Have you tried HttpServerUtility.UrlDecode
or HttpUtility.UrlDecode
?
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))