On Linux or MingW, with GNU toolchain:
ar -M <<EOM
CREATE libab.a
ADDLIB liba.a
ADDLIB libb.a
SAVE
END
EOM
ranlib libab.a
Of if you do not delete liba.a
and libb.a
, you can make a "thin archive":
ar crsT libab.a liba.a libb.a
On Windows, with MSVC toolchain:
lib.exe /OUT:libab.lib liba.lib libb.lib
I created a Kotlin extension function that simplifies the operation for Kotlin developers based on @Jason Robinson's answer. I hope it helps.
fun Bitmap.fixRotation(uri: Uri): Bitmap? {
val ei = ExifInterface(uri.path)
val orientation: Int = ei.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage( 90f)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage( 180f)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage( 270f)
ExifInterface.ORIENTATION_NORMAL -> this
else -> this
}
}
fun Bitmap.rotateImage(angle: Float): Bitmap? {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
this, 0, 0, width, height,
matrix, true
)
}
You can use Jquery's on method and listen for the scroll
event.
This works and convert to String as a Bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps
Providing A Custom Timestamp Format
If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:
class User extends Eloquent {
protected function getDateFormat()
{
return 'U';
}
}
https://laravel.com/docs/5.1/eloquent
If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:
class Flight extends Model
{
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'U';
}
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
I needed to download HLS video and audio streams from a e-learning portal with session-protected content with application/mp2t
MIME content type.
Manually copying all authentication headers into the downloading scripts would be too cumbersome.
But the task got much easier with help of Video DownloadHelper Firefox extension and it's Companion App. It allowed to download both m3u8 playlists with TS chunks lists and actual video and audio streams into mp4 files via a click of button while correctly preserving authentication headers.
The resulting separate video and audio files can be merged with ffmpeg:
ffmpeg -i video.mp4 -i audio.mp4 -acodec copy -vcodec copy video-and-audio.mp4
or with mp4box:
mp4box -add audio.mp4#audio video.mp4 -out video-and-audio.mp4
Tried Video DownloadHelper Chrome extension too, but it didn't work for me.
Easiest
eval(myvar)(parameter1, parameter2)
You don't have a function "pointer". You have a function "name".
While this works well, you will have a large number of folks telling you it's "insecure" or a "security risk".
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
this main
works in both linux and windows - found it through trial and error and help from others so can't explain why it works, it just does int main(int argc, char** argv)
no tchar.h
necessary
and here is the same answer in Wikipedia Main function
In an undirected graph (excluding multigraphs), the answer is n*(n-1)/2. In a directed graph an edge may occur in both directions between two nodes, then the answer is n*(n-1).
Example
So, if we had a child element with an id of "child-element" and we wanted to get it's left/top position relative to a parent element, say a div that had a class of "item-parent", we'd use this code.
var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);
Plugin Finally, for the actual plugin (with a few notes expalaining what's going on):
// offsetRelative (or, if you prefer, positionRelative)
(function($){
$.fn.offsetRelative = function(top){
var $this = $(this);
var $parent = $this.offsetParent();
var offset = $this.position();
if(!top) return offset; // Didn't pass a 'top' element
else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to
else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to
else { // Get parent's relative offset
var parent_offset = $parent.offsetRelative(top);
offset.top += parent_offset.top;
offset.left += parent_offset.left;
return offset;
}
};
$.fn.positionRelative = function(top){
return $(this).offsetRelative(top);
};
}(jQuery));
Note : You can Use this on mouseClick or mouseover Event
$(this).offsetRelative("div.item-parent");
Why not try the following in the init script:
setuid $USER application_name
It worked for me.
promises
, a JavaScript feature of the ECMAScript 6
standard. If your target platform does not support promises
, polyfill it with PromiseJs.You can get the Deferred
object jQuery creates for the animation using .promise()
on the animation call. Wrapping these Deferreds
into ES6 Promises
results in much cleaner code than using timers.
You can also use Deferreds
directly, but this is generally discouraged because they do not follow the Promises/A+ specification.
The resulting code would look like this:
var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});
Note that the function in Promise.all()
returns the promise. This is where magic happens. If in a then
call a promise is returned, the next then
call will wait for that promise to be resolved before executing.
jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!
I have disabled the jQuery animation queue to demonstrate how it would work with promises.
Promise.all()
takes an array of promises and creates a new Promise
that finishes after all promises in the array finished.
Promise.race()
also takes an array of promises, but finishes as soon as the first Promise
finished.
There's actually a great Google API for this. It takes in a location and returns the timezone for that location. Should be simple enough to create a bash or python script to get the results for each address in a CSV file or database then save the timezone information.
https://developers.google.com/maps/documentation/timezone/start
Request Endpoint:
https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119×tamp=1458000000&key=YOUR_API_KEY
Response:
{
"dstOffset" : 3600,
"rawOffset" : -18000,
"status" : "OK",
"timeZoneId" : "America/New_York",
"timeZoneName" : "Eastern Daylight Time"
}
Create the index.blade.php file in the views folder, that should be all
Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:
function compute() {
if ( $('input[name=type]:checked').val() != undefined ) {
var a = parseInt($('input[name=service_price]').val());
var b = parseInt($('input[name=modem_price]').val());
var total = a+b;
$('#total_price').val(a+b);
}
}
and this should work.
Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
Please do NOT try to set $DISPLAY manually when connecting over SSH.
If you connect via SSH -X
and $DISPLAY stays empty, this usually means that no encrypted channel could be established.
Most likely you are missing the package xauth
or xorg-x11-xauth
. Try to install it on the remote machine using:
sudo apt-get install xauth
or
sudo apt-get install xorg-x11-xauth
After that end and restart your SSH connection. Don't forget to use SSH -X
so that X Window output is forwarded to your local machine.
Now try echo $DISPLAY
again to see if $DISPLAY has been set automatically by the SSH demon. It should show you a line with an IP address and a port.
A simple example would be
DECLARE @number INTEGER
DECLARE @length INTEGER
DECLARE @char NVARCHAR(10)
SET @number = 1
SET @length = 5
SET @char = '0'
SELECT FORMAT(@number, replicate(@char, @length))
Try this connection string.
Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=yourDataBaseName;Integrated Security=True
See this link for more details http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.110%29.aspx
I prefer to turn the tibble to data.frame. It shows everything and you're done
df %>% data.frame
When you want to create interval store promise to variable:
var p = $interval(function() { ... },1000);
And when you want to stop / clear the interval simply use:
$interval.cancel(p);
You might sort the helper[]
array directly:
java.util.Arrays.sort(helper, 1, helper.length);
Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.
Alternatively, if you have Node.js installed, you can use the following command:
npx degit GIT_REPO
npx
comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit
globally using npm i -g degit
).
Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...
GROUP BY CONCAT(col1, '_', col2)
There is a much simpler way. This does not care if it is binary or text file.
Use noskipws.
char buf[SZ];
ifstream f("file");
int i;
for(i=0; f >> noskipws >> buffer[i]; i++);
ofstream f2("writeto");
for(int j=0; j < i; j++) f2 << noskipws << buffer[j];
Or you can just use string instead of the buffer.
string s; char c;
ifstream f("image.jpg");
while(f >> noskipws >> c) s += c;
ofstream f2("copy.jpg");
f2 << s;
normally stream skips white space characters like space or new line, tab and all other control characters. But noskipws makes all the characters transferred. So this will not only copy a text file but also a binary file. And stream uses buffer internally, I assume the speed won't be slow.
Because OPcache is designed to replace the APC module, it is not possible to run them in parallel in PHP. This is fine for caching PHP opcode as neither affects how you write code.
However it means that if you are currently using APC to store other data (through the apc_store()
function) you will not be able to do that if you decide to use OPCache.
You will need to use another library such as either APCu or Yac which both store data in shared PHP memory, or switch to use something like memcached, which stores data in memory in a separate process to PHP.
Also, OPcache has no equivalent of the upload progress meter present in APC. Instead you should use the Session Upload Progress.
The documentation for OPcache can be found here with all of the configuration options listed here. The recommended settings are:
; Sets how much memory to use
opcache.memory_consumption=128
;Sets how much memory should be used by OPcache for storing internal strings
;(e.g. classnames and the files they are contained in)
opcache.interned_strings_buffer=8
; The maximum number of files OPcache will cache
opcache.max_accelerated_files=4000
;How often (in seconds) to check file timestamps for changes to the shared
;memory storage allocation.
opcache.revalidate_freq=60
;If enabled, a fast shutdown sequence is used for the accelerated code
;The fast shutdown sequence doesn't free each allocated block, but lets
;the Zend Engine Memory Manager do the work.
opcache.fast_shutdown=1
;Enables the OPcache for the CLI version of PHP.
opcache.enable_cli=1
If you use any library or code that uses code annotations you must enable save comments:
opcache.save_comments=1
If disabled, all PHPDoc comments are dropped from the code to reduce the size of the optimized code. Disabling "Doc Comments" may break some existing applications and frameworks (e.g. Doctrine, ZF2, PHPUnit)
Use the following code in your controller:
return Json(new { success = string }, JsonRequestBehavior.AllowGet);
and in JavaScript:
success: function (data) {
var response = data.success;
....
}
Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.
#left{
float: left;
margin-right: 40px;
}
#right{
float: left;
}
When using git you can incorporate the newest facebook-android-sdk with ease.
git submodule add
https://github.com/facebook/facebook-android-sdk.git
include ':facebook-android-sdk:facebook'
compile
project(':facebook-android-sdk:facebook')
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
var toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
myArray = myArray.filter(ar => !toRemove.find(rm => (rm.name === ar.name && ar.place === rm.place) ))
You can use casting in the select clause like:
SELECT id, name, CAST(hide AS BOOLEAN) FROM table_name;
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/
or /mnt/sdcard/
. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/
somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/
without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
You can select the columns of a groupby:
In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
Y1961 Y1962 Y1963
Country Item_Code
Afghanistan 15 10 20 30
25 10 20 30
Angola 15 30 40 50
25 30 40 50
Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.
Search, charts, one-click setup....
Firebase.remove()
like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:
parent = ref.parent()
parent.on('child_removed', function (snapshot) {
// removed!
})
ref.remove()
According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove
method:
ref.remove(function (error) {
if (!error) {
// removed!
}
}
I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.
Perhaps you should think about using JQuery to apply common functionality to your form components?
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
I just had this problem and fixed it this way. I noticed the error message has jre in it not jre6 or jre7, so i copied jre6 from program files to eclipse folder then renamed it from jre6 to jre, then it worked :p
great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..
if (model is ViewDataDictionary)
{
controller.ViewData = model as ViewDataDictionary;
} else {
controller.ViewData.Model = model;
}
The nested class doesn't know about the outer class, and protected
doesn't help. You'll have to pass some actual reference to objects of the nested class type. You could store a foo*
, but perhaps a reference to the integer is enough:
class Outer
{
int n;
public:
class Inner
{
int & a;
public:
Inner(int & b) : a(b) { }
int & get() { return a; }
};
// ... for example:
Inner inn;
Outer() : inn(n) { }
};
Now you can instantiate inner classes like Inner i(n);
and call i.get()
.
I don't find it very intuitive reading new Singleton()
. You have to read the docs to know that new
isn't actually creating a new instance, as it normally would.
Here's another way to do singletons (Basically what Andrew said above).
lib/thing.dart
library thing;
final Thing thing = new Thing._private();
class Thing {
Thing._private() { print('#2'); }
foo() {
print('#3');
}
}
main.dart
import 'package:thing/thing.dart';
main() {
print('#1');
thing.foo();
}
Note that the singleton doesn't get created until the first time the getter is called due to Dart's lazy initialization.
If you prefer you can also implement singletons as static getter on the singleton class. i.e. Thing.singleton
, instead of a top level getter.
Also read Bob Nystrom's take on singletons from his Game programming patterns book.
the major difference between greedy method and dynamic programming is in greedy method only one optimal decision sequence is ever generated and in dynamic programming more than one optimal decision sequence may be generated.
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
[Closure and strong reference cycles]
As you know Swift's closure can capture the instance. It means that you are able to use self
inside a closure. Especially escaping closure
[About] can create a strong reference cycle
[About]. By the way you have to explicitly use self
inside escaping closure
.
Swift closure has Capture List
feature which allows you to avoid such situation and break a reference cycle because do not have a strong reference to captured instance. Capture List element is a pair of weak
/unowned
and a reference to class or variable.
For example
class A {
private var completionHandler: (() -> Void)!
private var completionHandler2: ((String) -> Bool)!
func nonescapingClosure(completionHandler: () -> Void) {
print("Hello World")
}
func escapingClosure(completionHandler: @escaping () -> Void) {
self.completionHandler = completionHandler
}
func escapingClosureWithPArameter(completionHandler: @escaping (String) -> Bool) {
self.completionHandler2 = completionHandler
}
}
class B {
var variable = "Var"
func foo() {
let a = A()
//nonescapingClosure
a.nonescapingClosure {
variable = "nonescapingClosure"
}
//escapingClosure
//strong reference cycle
a.escapingClosure {
self.variable = "escapingClosure"
}
//Capture List - [weak self]
a.escapingClosure {[weak self] in
self?.variable = "escapingClosure"
}
//Capture List - [unowned self]
a.escapingClosure {[unowned self] in
self.variable = "escapingClosure"
}
//escapingClosureWithPArameter
a.escapingClosureWithPArameter { [weak self] (str) -> Bool in
self?.variable = "escapingClosureWithPArameter"
return true
}
}
}
weak
- more preferable, use it when it is possibleunowned
- use it when you are sure that lifetime of instance owner is bigger than closureUse pm2 to start and run your nodejs processes on windows.
Be sure to read this github discussion of how to set up task scheduler to start pm2: https://github.com/Unitech/pm2/issues/1079
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :
The checked content attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />
The following are invalid:
<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text" />
Recommendation
If you care about writing valid XHTML, use disabled="disabled"
, since <input disabled>
is invalid and other alternatives are less readable. Else, just use <input disabled>
as it is shorter.
If you want a rounded corner only to one corner or two corners, etc... read this post:
[ObjC] – UIButton with rounded corner - http://goo.gl/kfzvKP
It's a XIB/Storyboard subclass. Import and set borders without write code.
First of all: officially, the correct question would be
web services + WSDL + SOAP
vsREST
.Because, although the web service, is used in the loose sense, when using the HTTP protocol to transfer data instead of web pages, officially it is a very specific form of that idea. According to the definition, REST is not "web service".
In practice however, everyone ignores that, so let's ignore it too
There are already technical answers, so I'll try to provide some intuition.
Let's say you want to call a function in a remote computer, implemented in some other programming language (this is often called remote procedure call/RPC). Assume that function can be found at a specific URL, provided by the person who wrote it. You have to (somehow) send it a message, and get some response. So, there are two main questions to consider.
For the first question, the official definition is WSDL. This is an XML file which describes, in detailed and strict format, what are the parameters, what are their types, names, default values, the name of the function to be called, etc. An example WSDL here shows that the file is human-readable (but not easily).
For the second question, there are various answers. However, the only one used in practice is SOAP. Its main idea is: wrap the previous XML (the actual message) into yet another XML (containing encoding info and other helpful stuff), and send it over HTTP. The POST method of the HTTP is used to send the message, since there is always a body.
The main idea of this whole approach is that you map a URL to a function, that is, to an action. So, if you have a list of customers in some server, and you want to view/update/delete one, you must have 3 URLS:
myapp/read-customer
and in the body of the message, pass the id of the customer to be read.myapp/update-customer
and in the body, pass the id of the customer, as well as the new datamyapp/delete-customer
and the id in the bodyThe REST approach sees things differently. A URL should not represent an action, but a thing (called resource in the REST lingo). Since the HTTP protocol (which we are already using) supports verbs, use those verbs to specify what actions to perform on the thing.
So, with the REST approach, customer number 12 would be found on URL myapp/customers/12
. To view the customer data, you hit the URL with a GET request. To delete it, the same URL, with a DELETE verb. To update it, again, the same URL with a POST verb, and the new content in the request body.
For more details about the requirements that a service has to fulfil to be considered truly RESTful, see the Richardson maturity model. The article gives examples, and, more importantly, explains why a (so-called) SOAP service, is a level-0 REST service (although, level-0 means low compliance to this model, it's not offensive, and it is still useful in many cases).
Or even better, use HTML elements that fit your need. It's cleaner, and produces leaner markup. Example:
<dl>
<dt>Lorem Ipsum etc <em>here</em></dt>
<dd>blah</dd>
<dd>blah blah</dd>
<dd>blah</dd>
<dt>lorem ipsums <em>and here</em></dt>
</dl>
Float the em
to the right (with display: block
), or set it to position: absolute
with its parent as position: relative
.
Have a look at this. The only way to solve it is by javascript as you tried.
EDIT: Try changing the event to keypressup.
And for webkit enabled browsers I've had good results with:
.myElement {
-webkit-overflow-scrolling: touch;
scroll-behavior: smooth; // Added in from answer from Felix
overflow-x: scroll;
}
This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!
Hope that helps,
Ed
First select the Database using use testDB;
then execute
desc `testDB`.`images`;
-- or
SHOW FIELDS FROM images;
Output:
I solve the same problem with this SO answer.
Basically it binds the radio button to a boolean property of a Strongly Typed Model.
@Html.RadioButton("blah", !Model.blah) Yes
@Html.RadioButton("blah", Model.blah) No
Hope it helps!
It may be worth considering if having your menu without any associated scope is the right way to go. Its not really the angular way.
But, if it is the way you need to go, then you can do it by adding the functions to $rootScope and then within those functions using $broadcast to send events. your controller then uses $on to listen for those events.
Another thing to consider if you do end up having your menu without a scope is that if you have multiple routes, then all of your controllers will have to have their own upate and get functions. (this is assuming you have multiple controllers)
This simple code will also work, to remove for example double quote from a string surrounded with double quote:
var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"(.+)"/g, '$1'));
You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.
For your purpose, it would make most sense to define a custom filter, so you could for example do the following:
The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{ splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{ splitpart(1) }}
The filter function could then look like this:
def splitpart (value, index, char = ','):
return value.split(char)[index]
An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.
this error occurred sometime method attribute ( valid passing method ) Error option : method="get" but called by $Fname = $_POST["name"]; or
method="post" but called by $Fname = $_GET["name"];
More info visit http://www.doordie.co.in/index.php
There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.
Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>
. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.
Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.
As stated by Buffernet, you cannot use a distribution provisioning profile to debug. When I switched to a developer provisioning profile, I got the error "A Valid Provisioning Profile For This Executable Was Not Found".
A quick google for this lead me to the article listed below. From there, I realised that I hadn't got a valid development provisioning profile as my iPhone hadn't been added to the Provisioning Portal and all the other stuff involved.
Make sure you run an iPhone developer provisioning profile and your device has been added to the provisioning portal!
I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.
The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?
Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.
It's simple; make a custom cell and take a outlet of button
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.yourButton.tag = indexPath.Row;
- (void)buttonPressedAction:(id)sender
change id in above method to (UIButton *)
You can get the value that which button is being tapped by doing sender.tag.
I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat
. The Concat
method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains
, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:
// Given an array of id's
var ids = new Guid[] { ... };
// and a DataContext
var dc = new MyDataContext();
// start the queryable
var query = (
from thing in dc.Things
where thing.Id == ids[ 0 ]
select thing
);
// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
// select that thing and concat to queryable
query.Concat(
from thing in dc.Things
where thing.Id == ids[ i ]
select thing
);
}
This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.
I set up a test where I did 100 trials each of Concat
and Contains
where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat
method comes out 5 - 10% faster, although one time the Contains
method won by just a smidgen.
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
<script type="text/javascript">
$(document).ready(function () {
$('#btnadd').on('click', function () {
var n1 = parseInt($('#txtn1').val());
var n2 = parseInt($('#txtn2').val());
var r = n1 + n2;
alert("sum of 2 No= " + r);
return false;
});
$('#btnclear').on('click', function () {
$('#txtn1').val('');
$('#txtn2').val('');
$('#txtn1').focus();
return false;
});
});
</script>
Even though I realise this is an old question, I'd like to suggest using the traceback
module to handle output of the exceptions.
Use traceback.print_exc()
to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc()
to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.
In case that helps anybody I had the same issue with wampserver3.2.0_x64 on Windows 10 Enterprise.
Tried everything from the answers of this thread and nothing helped.
I then installed wampserver3.1.0_x86 instead and got the green light on first launch. I have no explanation but at least the desired end result.
I had a similar error and my problem was that the name and case of the variable name and constructor name were identical, which doesn't work since javascript interprets the intended constructor as the newly created variable.
In other words:
function project(name){
this.name = name;
}
//elsewhere...
//this is no good! name/case are identical so javascript barfs.
let project = new project('My Project');
Simply changing case or variable name fixes the problem, though:
//with a capital 'P'
function Project(name){
this.name = name;
}
//elsewhere...
//works! class name/case is dissimilar to variable name
let project = new Project('My Project');
Modify Global.asax.cs
, including the Application_Start
event with:
Database.SetInitializer<YourDatabaseContext>(
new DropCreateDatabaseIfModelChanges<YourDatabaseContext>());
string uriPath =
"file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;
If using another library is an option, the following may be easier:
package for_so;
import java.io.File;
import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;
public class Q7704827_SimpleRead
{
public static void
main(String[] args)
{
String fileName = args[0];
TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
String recipient = emailNode.nextTextFieldE("recipient");
String sender = emailNode.nextTextFieldE("sender");
String subject = emailNode.nextTextFieldE("subject");
String description = emailNode.nextTextFieldE("description");
emailNode.verifyNoMoreChildren();
System.out.println("recipient = " + recipient);
System.out.println("sender = " + sender);
System.out.println("subject = " + subject);
System.out.println("desciption = " + description);
}
}
The library and its documentation are at rasmustorkel.com
Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.
Watching this course https://app.pluralsight.com/library/courses/angular-2-getting-started-update/discussion
The author explains that new version of JavaScript has for of and for in, the for of is to enumerate objects and the for in is to enumerate the index of the array.
use moment in your function like this
moment(new Date(date)).format('MM/DD/YYYY')
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!
The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this :
mysql --help | grep Default -A 1
And the output:
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
--
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
--
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
--
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
--
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
As a workaround until the compiler allows overriding the warning, you can use the runtime
objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));
instead of
[_controller performSelector:NSSelectorFromString(@"someMethod")];
You'll have to
#import <objc/message.h>
the following bitwise operators: &, |, ^, and ~ return values (based on their input) in the same way logic gates affect signals. You could use them to emulate circuits.
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
When you open catalina.sh / catalina.bat, you can see :
Environment Variable Prequisites
JAVA_HOME Must point at your Java Development Kit installation.
So, set your environment variable JAVA_HOME
to point to Java 6. Also make sure JRE_HOME
is pointing to the same target, if it is set.
Update: since you are on Windows, see here for how to manage your environment variables
You could check with:
($Member.PropertyNames -contains "Name")
this will check for the Named property
I created a UIImageView category for this, based on some of the answers above.
Header File:
@interface UIImageView (SaveImage) <UIActionSheetDelegate>
- (void)addHoldToSave;
@end
Implementation
@implementation UIImageView (SaveImage)
- (void)addHoldToSave{
UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0f;
[self addGestureRecognizer:longPress];
}
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
UIActionSheet* _attachmentMenuSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Save Image", nil];
[_attachmentMenuSheet showInView:[[UIView alloc] initWithFrame:self.frame]];
}
else if (sender.state == UIGestureRecognizerStateBegan){
//Do nothing
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
UIImageWriteToSavedPhotosAlbum(self.image, nil,nil, nil);
}
}
@end
Now simply call this function on your imageview:
[self.imageView addHoldToSave];
Optionally you can alter the minimumPressDuration parameter.
Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!
struct Coordinate
{
int x,y;
};
void resize( int **p, int size )
{
free( *p );
*p = (int*) malloc( size * sizeof(int) );
}
void resizeCoord( struct Coordinate **p, int size )
{
free( *p );
*p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}
void resizeCoordWithNew( struct Coordinate **p, int size )
{
delete [] *p;
*p = (struct Coordinate*) new struct Coordinate[size];
}
void SomeMethod(Coordinate Coordinates[])
{
Coordinates[0].x++;
Coordinates[0].y = 6;
}
void SomeOtherMethod(Coordinate Coordinates[], int size)
{
for (int i=0; i<size; i++)
{
Coordinates[i].x = i;
Coordinates[i].y = i*2;
}
}
int main()
{
//static array
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates);
SomeMethod(&(tenCoordinates[0]));
if(tenCoordinates[0].x - 2 == 0)
{
printf("test1 coord change successful\n");
}
else
{
printf("test1 coord change unsuccessful\n");
}
//dynamic int
int *p = (int*) malloc( 10 * sizeof(int) );
resize( &p, 20 );
//dynamic struct with malloc
int myresize = 20;
int initSize = 10;
struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
resizeCoord(&pcoord, myresize);
SomeOtherMethod(pcoord, myresize);
bool pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
pass = false;
}
}
if (pass)
{
printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
}
//dynamic struct with new
myresize = 20;
initSize = 10;
struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
resizeCoordWithNew(&pcoord2, myresize);
SomeOtherMethod(pcoord2, myresize);
pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
pass = false;
}
}
if (pass)
{
printf("test3 coords for dynamic struct with new worked correctly\n");
}
return 0;
}
var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();
var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';
Check the jQuery API docs for information on each:
Here's the edited jsFiddle showing the result.
You can perform the same type of operations for the Height to get its margin, border, and padding.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.
When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?
Use the RegExp constructor and multiple replacements to clarify the syntax:
function getCook(cookiename)
{
// Get name followed by anything except a semicolon
var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
// Return everything after the equal sign, or an empty string if the cookie name not found
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');
You can just run:
git stash pop
and it will unstash your changes.
If you want to preserve the state of files (staged vs. working), use
git stash apply --index
I suggest this discriminative question:
Is the open-source tool necessary in your process of making money?
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
Try the QuickTime Player! Heres my JavaScript that generates the embedded object on a web page and plays the stream:
//SET THE RTSP STREAM ADDRESS HERE
var address = "rtsp://192.168.0.101/mpeg4/1/media.3gp";
var output = '<object width="640" height="480" id="qt" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">';
output += '<param name="src" value="'+address+'">';
output += '<param name="autoplay" value="true">';
output += '<param name="controller" value="false">';
output += '<embed id="plejer" name="plejer" src="/poster.mov" bgcolor="000000" width="640" height="480" scale="ASPECT" qtsrc="'+address+'" kioskmode="true" showlogo=false" autoplay="true" controller="false" pluginspage="http://www.apple.com/quicktime/download/">';
output += '</embed></object>';
//SET THE DIV'S ID HERE
document.getElementById("the_div_that_will_hold_the_player_object").innerHTML = output;
It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.
It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.
In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.
A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.
Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.
In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.
The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.
For example:
class A(object):
def __init__(self):
self.__foobar = None # will be automatically mangled to self._A__foobar
class B(A):
def __init__(self):
self.__foobar = 1 # will be automatically mangled to self._B__foobar
self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.
I strongly recommend to watch Raymond Hettingers talk "Pythons class development toolkit" from Pycon 2013 (should be available on Youtube), which gives a good example why and how you should use @property and "__"-instance variables.
If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:
class Distance:
def __init__(self, meter):
self.meter = meter
d = Distance(1.0)
print(d.meter)
# prints 1.0
class Distance:
def __init__(self, meter):
# Customer request: Distances must be stored in millimeters.
# Public available internals must be changed.
# This would break client code in C++.
# This is why you never expose public variables in C++ or Java.
# However, this is python.
self.millimeter = meter * 1000
# In python we have @property to the rescue.
@property
def meter(self):
return self.millimeter *0.001
@meter.setter
def meter(self, value):
self.millimeter = meter * 1000
d = Distance(1.0)
print(d.meter)
# prints 1.0
It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1].
GManNickG answer's tells why this happen. But the best way to solve this is to put User
class in one header file (User.h
) and MyMessageBox
class in another header file (MyMessageBox.h
). Then in your User.h
you include MyMessageBox.h
and in MyMessageBox.h
you include User.h
. Do not forget "include gaurds" [2] so that your code compiles successfully.
You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.
You could set
table tr ul.actions {margin: 0; white-space:nowrap;}
(or set this for the last TD as Sander suggested instead).
This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.
This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space
-property is applied, stretching its content beyond the calculated boundaries.
So I guess it's not possible without having an element within the last TD with a specific width.
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
Note the use of cbegin()
and cend()
functions.
Easier still, you can use the range-based for loop:
for(auto elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
Kotlin Version
Simply use ViewPropertyAnimator
like this:
iv.alpha = 0.2f
iv.animate().apply {
interpolator = LinearInterpolator()
duration = 500
alpha(1f)
startDelay = 1000
start()
}
it looks like BC3 only supports 3 way merge for PRO Edition. http://www.scootersoftware.com/moreinfo.php?zz=kb_editions
I also made a library for this. It is fully configurable with a Mustache template. That can:
I also made:
More details on Github: https://github.com/tomasbjerre/git-changelog-lib
From command line:
npx git-changelog-command-line -std -tec "
# Changelog
Changelog for {{ownerName}} {{repoName}}.
{{#tags}}
## {{name}}
{{#issues}}
{{#hasIssue}}
{{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
{{/hasLink}}
{{/hasIssue}}
{{^hasIssue}}
### {{name}}
{{/hasIssue}}
{{#commits}}
**{{{messageTitle}}}**
{{#messageBodyItems}}
* {{.}}
{{/messageBodyItems}}
[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*
{{/commits}}
{{/issues}}
{{/tags}}
"
Or in Jenkins:
ALTER TABLE table_name RENAME TO new_table_name; works in MySQL as well.
I would say use an RDBMS if you need complex transactions. Otherwise I would go with MongoDB - more flexible to work with and you know it can scale when you need to. (I'm biased though - I work on the MongoDB project)
The typical answer is this:
In Excel, File/Save As, select CSV, save your current sheet.
transfer to a holding directory on the Pg server the postgres user can access
in PostgreSQL:
COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:
Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.
Use CSV and the fdw_file to access it as a pseudo-table
Use DBILink and DBD::Excel
Write your own foreign data wrapper for reading Excel files.
The possibilities are literally endless....
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence use printf
instead.
Yes this is possible. It is not enough you just copy the .frm
files to the to the databse folder but you also need to copy the ib_logfiles
and ibdata
file into your data folder. I have just copy the .frm
files and copy those files and just restart the server and my database is restored.
After copying the above files execute the following command -
sudo chown -R mysql:mysql /var/lib/mysql
The above command will change the file owner under mysql and it's folder to MySql user. Which is important for mysql to read the .frm
and ibdata
files.
I like using ICU4J’s CaseInsensitiveString wrap of the Map key because it takes care of the hash\equals and issue and it works for unicode\i18n.
HashMap<CaseInsensitiveString, String> caseInsensitiveMap = new HashMap<>();
caseInsensitiveMap.put("tschüß", "bye");
caseInsensitiveMap.containsKey("TSCHÜSS"); # true
first of all you need to setup line ending preferences in termnial
git config --global core.autocrlf input
git config --global core.safecrlf true
Then you can use :q
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
From what I understand you do not want to redirect when the link is clicked. You can do :
<a href='javascript:;' onclick='show_more_menu();'>More ></a>
So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:
HTML:
<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">
JS:
<script>
function initMap() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById("address").value = JSON.stringify(place.address_components);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
I was searching how to do something similar in WPF and I got this solution:
<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding}"
Command="{Binding Path=DataContext.CustomCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems
-which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate
is using a DataTemplate
, the DataContext
of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl
type.
Try:
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"
Then do another round of copy/paste of all the extensions (joined together with ;
as above) for "All graphics types":
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff"
In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture
:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs
When you write
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')
It can fixed
bar
is your static variable and you can access it using Foo.bar
.
Basically, you need to qualify your static variable with Class name.
I found them useful in a situation when I wanted to declare a handler for some control's event, using another control. To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.
private ComboBox combo;
private Label label;
public CreateControls()
{
combo = new ComboBox();
label = new Label();
//some initializing code
combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
label.Text = combo.SelectedValue;
}
thanks to lambda expressions you can use it like this:
public CreateControls()
{
ComboBox combo = new ComboBox();
Label label = new Label();
//some initializing code
combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}
Much easier.
I just found all the above examples just too confusing, so I wrote my own. Code fragments are fine if you know what you're doing, but what about people like me who don't?
Want a cut-n-paste solution instead? Well here it is!
Create a new java file and call it Keystore. Then paste in this code:
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class Keystore { //Did you remember to vote up my example?
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
Log.v("Keystore","NEW STORE");
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
Editor editor = SP.edit();
editor.putString(key, value);
editor.commit(); // Stop everything and do an immediate save!
// editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above. This is the preferred way of saving.
}
public String get(String key) {//Log.v("Keystore","GET from "+key);
return SP.getString(key, null);
}
public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
Editor editor = SP.edit();
editor.putInt(key, num);
editor.commit();
}
public void clear(){ // Delete all shared preferences
Editor editor = SP.edit();
editor.clear();
editor.commit();
}
public void remove(){ // Delete only the shared preference that you want
Editor editor = SP.edit();
editor.remove(filename);
editor.commit();
}
}
Now save that file and forget about it. You're done with it. Now go back into your activity and use it like this:
public class YourClass extends Activity{
private Keystore store;//Holds our key pairs
public YourSub(Context context){
store = Keystore.getInstance(context);//Creates or Gets our key pairs. You MUST have access to current context!
int= store.getInt("key name to get int value");
string = store.get("key name to get string value");
store.putInt("key name to store int value",int_var);
store.put("key name to store string value",string_var);
}
}
I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.
Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition
if false {
// Technically, svc still be used so no yelling
_, err = svc.SendRawEmail(input)
Check(err)
}
In Swift you would do it like this:
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
(Note that the way the lineBreakMode constant works is different to in ObjC)
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
basically, look for everything at the beginning except _
, and then the _2
.
+1 to @Ananda_Mahto for suggesting grepl
instead of grep
.
If you're really just annoyed at using try/except
s all over the place, please just write a helper function:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
Check out the scales
package. It used to be a part of ggplot2
, I think.
library('scales')
percent((1:10) / 100)
# [1] "1%" "2%" "3%" "4%" "5%" "6%" "7%" "8%" "9%" "10%"
The built-in logic for detecting the precision should work well enough for most cases.
percent((1:10) / 1000)
# [1] "0.1%" "0.2%" "0.3%" "0.4%" "0.5%" "0.6%" "0.7%" "0.8%" "0.9%" "1.0%"
percent((1:10) / 100000)
# [1] "0.001%" "0.002%" "0.003%" "0.004%" "0.005%" "0.006%" "0.007%" "0.008%"
# [9] "0.009%" "0.010%"
percent(sqrt(seq(0, 1, by=0.1)))
# [1] "0%" "32%" "45%" "55%" "63%" "71%" "77%" "84%" "89%" "95%"
# [11] "100%"
percent(seq(0, 0.1, by=0.01) ** 2)
# [1] "0.00%" "0.01%" "0.04%" "0.09%" "0.16%" "0.25%" "0.36%" "0.49%" "0.64%"
# [10] "0.81%" "1.00%"
You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :
git config --global http.sslverify false
enjoy git :)
If you have scp then:
To move your file from local to remote:
$scp /home/user/file.gz user@ipaddress:path/to/file.gz
To move your file from remote to local:
$scp user@ipaddress:path/to/file.gz /home/user/file.gz
To export your mysql file without login in to remote system:
$mysqldump -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p databasename | gzip -9 > databasename.sql.gz
To import your mysql file withoug login in to remote system:
$gunzip < databasename.sql.gz | mysql -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p
Note: Make sure you have network access to the ipaddress of remote host
To check network access:
$ping ipaddressofremotehost
Exec the query in TOAD or SQL DEVELOPER
---select /*csv*/ username, user_id, created from all_users;
Save in .SQL format in "C" drive
--- x.sql
execute command
---- set serveroutput on
spool y.csv
@c:\x.sql
spool off;
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
A few things I've been able to glean: apparently using a "mirror driver" is fast though I'm not aware of an OSS one.
Why is RDP so fast compared to other remote control software?
Also apparently using some convolutions of StretchRect are faster than BitBlt
http://betterlogic.com/roger/2010/07/fast-screen-capture/comment-page-1/#comment-5193
And the one you mentioned (fraps hooking into the D3D dll's) is probably the only way for D3D applications, but won't work with Windows XP desktop capture. So now I just wish there were a fraps equivalent speed-wise for normal desktop windows...anybody?
(I think with aero you might be able to use fraps-like hooks, but XP users would be out of luck).
Also apparently changing screen bit depths and/or disabling hardware accel. might help (and/or disabling aero).
https://github.com/rdp/screen-capture-recorder-program includes a reasonably fast BitBlt based capture utility, and a benchmarker as part of its install, which can let you benchmark BitBlt speeds to optimize them.
VirtualDub also has an "opengl" screen capture module that is said to be fast and do things like change detection http://www.virtualdub.org/blog/pivot/entry.php?id=290
use this: String customHtml =text ;
wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);
Using the Promise pattern:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
And when calling the function we can handle its response or error quite neatly.
getImage('imgUrl').then(function(successUrl){
//do stufff
}).catch(function(errorUrl){
//do stuff
})
python compile on the fly when you run it.
Run a .py file by(linux): python abc.py
Well to create extra elements we can use :after, :before (so we don’t have to change the HTML that much). Then for radio buttons and checkboxes we can use :checked. There are a few other pseudo elements we can use as well (such as :hover). Using a mixture of these we can create some pretty cool custom forms. check this
In my opinion, the important thing about the default export is that it can be imported with any name!
If there is a file, foo.js, which exports default:
export default function foo(){}
_x000D_
it can be imported in bar.js using:
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
Either the user doesn't have privileges needed to see the table, the table doesn't exist or you are running the query in the wrong schema
Does the table exist?
select owner,
object_name
from dba_objects
where object_name = any ('CUSTOMER','customer');
What privileges did you grant?
grant select, insert on customer to user;
Are you running the query against the owner from the first query?
$('textarea#message')
cannot be undefined (if by $
you mean jQuery of course).
$('textarea#message')
may be of length 0 and then $('textarea#message').val()
would be empty that's all
The closest thing to "for each" is probably MySQL Procedure using Cursor and LOOP.
Using some reflection and generics in two extension methods you can achieve that.
Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:
public static class ObjectExtensions
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();
foreach (var item in source)
{
someObjectType
.GetProperty(item.Key)
.SetValue(someObject, item.Value, null);
}
return someObject;
}
public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);
}
}
class A
{
public string Prop1
{
get;
set;
}
public int Prop2
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Prop1", "hello world!");
dictionary.Add("Prop2", 3893);
A someObject = dictionary.ToObject<A>();
IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
}
}
Change your storage engine to InnoDB by going to Operation
Adapting the PATH
should work. Just tried on my Git bash:
$ python --version
sh.exe": python: command not found
$ PATH=$PATH:/c/Python27/
$ python --version
Python 2.7.6
In particular, only provide the directory; don't specify the .exe
on the PATH
; and use slashes.
In addition to Michael Sorens' answer:
Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.
Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.
The where
statement gets executed before the order by
. So, your desired query is saying "take the first row and then order it by t_stamp
desc". And that is not what you intend.
The subquery method is the proper method for doing this in Oracle.
If you want a version that works in both servers, you can use:
select ril.*
from (select ril.*, row_number() over (order by t_stamp desc) as seqnum
from raceway_input_labo ril
) ril
where seqnum = 1
The outer *
will return "1" in the last column. You would need to list the columns individually to avoid this.
regular expression for validate 'abc' ignoring case sensitive
(?i)(abc)
If you need path only this is the most straightforward way:
PathOnly = ThisWorkbook.Path
I think what has been under-emphasized in the cited answers is the issue of duplicates and problematic results that may arise from specific (use) cases.
(although Marcelo Cantos does mention it)
I will cite the example from Stanford's Lagunita courses on SQL.
+------+--------+------+--------+
| sID | sName | GPA | sizeHS |
+------+--------+------+--------+
| 123 | Amy | 3.9 | 1000 |
| 234 | Bob | 3.6 | 1500 |
| 345 | Craig | 3.5 | 500 |
| 456 | Doris | 3.9 | 1000 |
| 567 | Edward | 2.9 | 2000 |
| 678 | Fay | 3.8 | 200 |
| 789 | Gary | 3.4 | 800 |
| 987 | Helen | 3.7 | 800 |
| 876 | Irene | 3.9 | 400 |
| 765 | Jay | 2.9 | 1500 |
| 654 | Amy | 3.9 | 1000 |
| 543 | Craig | 3.4 | 2000 |
+------+--------+------+--------+
(applications made to specific universities and majors)
+------+----------+----------------+----------+
| sID | cName | major | decision |
+------+----------+----------------+----------+
| 123 | Stanford | CS | Y |
| 123 | Stanford | EE | N |
| 123 | Berkeley | CS | Y |
| 123 | Cornell | EE | Y |
| 234 | Berkeley | biology | N |
| 345 | MIT | bioengineering | Y |
| 345 | Cornell | bioengineering | N |
| 345 | Cornell | CS | Y |
| 345 | Cornell | EE | N |
| 678 | Stanford | history | Y |
| 987 | Stanford | CS | Y |
| 987 | Berkeley | CS | Y |
| 876 | Stanford | CS | N |
| 876 | MIT | biology | Y |
| 876 | MIT | marine biology | N |
| 765 | Stanford | history | Y |
| 765 | Cornell | history | N |
| 765 | Cornell | psychology | Y |
| 543 | MIT | CS | N |
+------+----------+----------------+----------+
Let's try to find the GPA scores for students that have applied to CS
major (regardless of the university)
Using a subquery:
select GPA from Student where sID in (select sID from Apply where major = 'CS');
+------+
| GPA |
+------+
| 3.9 |
| 3.5 |
| 3.7 |
| 3.9 |
| 3.4 |
+------+
The average value for this resultset is:
select avg(GPA) from Student where sID in (select sID from Apply where major = 'CS');
+--------------------+
| avg(GPA) |
+--------------------+
| 3.6800000000000006 |
+--------------------+
Using a join:
select GPA from Student, Apply where Student.sID = Apply.sID and Apply.major = 'CS';
+------+
| GPA |
+------+
| 3.9 |
| 3.9 |
| 3.5 |
| 3.7 |
| 3.7 |
| 3.9 |
| 3.4 |
+------+
average value for this resultset:
select avg(GPA) from Student, Apply where Student.sID = Apply.sID and Apply.major = 'CS';
+-------------------+
| avg(GPA) |
+-------------------+
| 3.714285714285714 |
+-------------------+
It is obvious that the second attempt yields misleading results in our use case, given that it counts duplicates for the computation of the average value.
It is also evident that usage of distinct
with the join - based statement will not eliminate the problem, given that it will erroneously keep one out of three occurrences of the 3.9
score. The correct case is to account for TWO (2) occurrences of the 3.9
score given that we actually have TWO (2) students with that score that comply with our query criteria.
It seems that in some cases a sub-query is the safest way to go, besides any performance issues.
If you wish to clear your entire database.
Because of the foreign-key constraints it matters which sequence the tables are truncated. This is a way to bruteforce this sequence.
public static void ClearDatabase<T>() where T : DbContext, new()
{
using (var context = new T())
{
var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList();
foreach (var tableName in tableNames)
{
foreach (var t in tableNames)
{
try
{
if (context.Database.ExecuteSqlCommand(string.Format("TRUNCATE TABLE [{0}]", tableName)) == 1)
break;
}
catch (Exception ex)
{
}
}
}
context.SaveChanges();
}
}
usage:
ClearDatabase<ApplicationDbContext>();
remember to reinstantiate your DbContext after this.
EDITED
You can look into sys.tables for checking existence desired table:
IF NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')
BEGIN
CREATE TABLE [SchemaName].[YourTable](
....
....
....
)
END
CR and LF are control characters, respectively coded 0x0D
(13 decimal) and 0x0A
(10 decimal).
They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.
An apocryphal historical perspective:
As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)
Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.
Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String)
. You use it like Double.parseDouble
but it returns null
rather than throwing an exception if the string does not parse to a double.
You're using JSTL 2.0 right? You don't need to put <c:out/>
around all variables. Have you tried something like this?
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
<c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>
Edit: Beaten by the above
This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.
Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.
On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.
Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.
This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).
Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.
Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.
A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.
From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.
From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.
However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!
The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:
develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).
bind to a specific version of the API (which becomes apparent) but only for a limited time
For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):
http://shonzilla/api/customers/1234 http://shonzilla/api/v3.0/customers/1234 http://shonzilla/api/v3/customers/1234
In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:
http://shonzilla/api/v2.2/customers/1234 http://shonzilla/api/v2.0/customers/1234 http://shonzilla/api/v2/customers/1234 http://shonzilla/api/v1.1/customers/1234 http://shonzilla/api/v1/customers/1234
should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location
HTTP header that redirects to the appropriate version of resource URI which remain to be this one:
http://shonzilla/api/customers/1234
There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:
301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.
302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).
other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification
The PropTypes documentation has the following
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
So, you can use PropTypes.node
to check for objects or arrays of objects
static propTypes = {
children: PropTypes.node.isRequired,
}
As hanry has mentioned above putting liner iterpolator is fine. But if rotation is inside a set you must put android:shareInterpolator="false" to make it smooth.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
**android:shareInterpolator="false"**
>
<rotate
android:interpolator="@android:anim/linear_interpolator"
android:duration="300"
android:fillAfter="true"
android:repeatCount="10"
android:repeatMode="restart"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:duration="3000"
android:fillAfter="true"
android:pivotX="50%"
android:pivotY="50%"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="0"
android:toYScale="0" />
</set>
If Sharedinterpolator being not false, the above code gives glitches.
I've implemented this to send Cyrillic e-mails through my MS Exchange server.
function to_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;
Try it.
upd: after a minor adjustment I came up with this, so it works both ways now:
function from_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;
You can check it:
SQL> set serveroutput on
SQL>
SQL> declare
2 function to_base64(t in varchar2) return varchar2 is
3 begin
4 return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
5 end to_base64;
6
7 function from_base64(t in varchar2) return varchar2 is
8 begin
9 return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw (t)));
10 end from_base64;
11
12 begin
13 dbms_output.put_line(from_base64(to_base64('asdf')));
14 end;
15 /
asdf
PL/SQL procedure successfully completed
upd2: Ok, here's a sample conversion that works for CLOB
I just came up with. Try to work it out for your blobs. :)
declare
clobOriginal clob;
clobInBase64 clob;
substring varchar2(2000);
n pls_integer := 0;
substring_length pls_integer := 2000;
function to_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;
function from_base64(t in varchar2) return varchar2 is
begin
return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;
begin
select clobField into clobOriginal from clobTable where id = 1;
while true loop
/*we substract pieces of substring_length*/
substring := dbms_lob.substr(clobOriginal,
least(substring_length, substring_length * n + 1 - length(clobOriginal)),
substring_length * n + 1);
/*if no substring is found - then we've reached the end of blob*/
if substring is null then
exit;
end if;
/*convert them to base64 encoding and stack it in new clob vadriable*/
clobInBase64 := clobInBase64 || to_base64(substring);
n := n + 1;
end loop;
n := 0;
clobOriginal := null;
/*then we do the very same thing backwards - decode base64*/
while true loop
substring := dbms_lob.substr(clobInBase64,
least(substring_length, substring_length * n + 1 - length(clobInBase64)),
substring_length * n + 1);
if substring is null then
exit;
end if;
clobOriginal := clobOriginal || from_base64(substring);
n := n + 1;
end loop;
/*and insert the data in our sample table - to ensure it's the same*/
insert into clobTable (id, anotherClobField) values (1, clobOriginal);
end;
Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.
lol, it has a very easy solution with CSS only. Here you go
#thing { padding: 10px; border-radius: 5px;
/* HOVER OFF */ -webkit-transition: padding 2s; }
#thing:hover { padding: 20px; border-radius: 15px;
/* HOVER ON */ -webkit-transition: border-radius 2s; }
This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:
Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)
@Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
Use Javascript to open a new window
window.open("Link URL")
Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:
a = (1, 2, 3)
b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6)
c = b[1:] # (2, 3, 4, 5, 6)
And, of course, build them from existing values:
name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)
To activate the menus and submenus, even with params in the URL, use the code bellow:
// Highlight the active menu
$(document).ready(function () {
var action = window.location.pathname.split('/')[1];
// If there's no action, highlight the first menu item
if (action == "") {
$('ul.nav li:first').addClass('active');
} else {
// Highlight current menu
$('ul.nav a[href="/' + action + '"]').parent().addClass('active');
// Highlight parent menu item
$('ul.nav a[href="/' + action + '"]').parents('li').addClass('active');
}
});
This accepts URLs like:
/posts
/posts/1
/posts/1/edit
It's probably more than solved. Just want to contribute with another simple solution:
var text = 'uololooo';
// With ES6
[...text].forEach(c => console.log(c))
// With the `of` operator
for (const c of text) {
console.log(c)
}
// With ES5
for (var x = 0, c=''; c = text.charAt(x); x++) {
console.log(c);
}
// ES5 without the for loop:
text.split('').forEach(function(c) {
console.log(c);
});
I know this question is several years old, but what I think you're trying to do is get it so where a large element, like an image doesn't interfere with the height of a div?
I just ran into something similar, where I wanted an image to overflow a div, but I wanted it to be at the end of a string of text, so I didn't know where it would end up being.
A solution I figured out was to put the margin-bottom: -element's height, so if the image is 20px hight,
margin-bottom: -20px;
vertical-align: top;
for example.
That way it floated over the outside of the div, and stayed next to the last word in the string.
I had a lot of problems making a virtual environment (venv) as described in the tensorflow installation guide.
Most of the commands listed in this post didn't help me either so, if this is also your case this is what I did:
pip3 install --user pipenv
pip install virtualenv
Installs the dependencies to create a virtual environment
mkdir myenv
Makes a new directory called myenv but you can call it whatever you want e.g. mynewenv
cd myenv
Or whatever you call your directory so: cd [your_directory_name]
virtualenv -p /usr/bin/python3 venv
Creates a virtual environment called venv in the folder myenv. You can call your virtual env whatever you like e.g. vitualenv [v_env_name]
source ./venv/bin/activate
Activates the virtual environment. Note that if you choose a different v. env. name your commands should be written as such source ./[v_env_name]/bin/activate
deactivate
Deactivates the virtual environment.
Note: I am using Python 3.6.6 & Ubuntu 18.04
You do not need to use the while True:
loop in this case. There is a much simpler way to use the time condition directly:
import time
# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
test = 0
if test == 5:
break
test -= 1
Checked out the ObjectIDGenerator class? This does what you're attempting to do, and what Marc Gravell describes.
The ObjectIDGenerator keeps track of previously identified objects. When you ask for the ID of an object, the ObjectIDGenerator knows whether to return the existing ID, or generate and remember a new ID.
The IDs are unique for the life of the ObjectIDGenerator instance. Generally, a ObjectIDGenerator life lasts as long as the Formatter that created it. Object IDs have meaning only within a given serialized stream, and are used for tracking which objects have references to others within the serialized object graph.
Using a hash table, the ObjectIDGenerator retains which ID is assigned to which object. The object references, which uniquely identify each object, are addresses in the runtime garbage-collected heap. Object reference values can change during serialization, but the table is updated automatically so the information is correct.
Object IDs are 64-bit numbers. Allocation starts from one, so zero is never a valid object ID. A formatter can choose a zero value to represent an object reference whose value is a null reference (Nothing in Visual Basic).
For synchronous renaming use fs.renameSync
fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
As others have mentioned, this is a really tricky question. Solutions to this are not "one size fits all", not even remotely. The difficulty (or ease) is really going to depend on your situation.
I have come to this problem on several occasions, but most recently while creating a debugging function. I wanted the function to take some unknown objects as arguments and print their declared names and contents. Getting the contents is easy of course, but the declared name is another story.
What follows is some of what I have come up with.
Determining the name of a function is really easy as it has the __name__ attribute containing the function's declared name.
name_of_function = lambda x : x.__name__
def name_of_function(arg):
try:
return arg.__name__
except AttributeError:
pass`
Just as an example, if you create the function def test_function(): pass
, then copy_function = test_function
, then name_of_function(copy_function)
, it will return test_function.
Check whether the object has a __name__ attribute and return it if so (declared functions only). Note that you may remove this test as the name will still be in globals()
.
Compare the value of arg with the values of items in globals()
and return the name of the first match. Note that I am filtering out names starting with '_'.
The result will consist of the name of the first matching object otherwise None.
def name_of_object(arg):
# check __name__ attribute (functions)
try:
return arg.__name__
except AttributeError:
pass
for name, value in globals().items():
if value is arg and not name.startswith('_'):
return name
globals()
and store names in a list. Note that I am filtering out names starting with '_'.The result will consist of a list (for multiple matches), a string (for a single match), otherwise None. Of course you should adjust this behavior as needed.
def names_of_object(arg):
results = [n for n, v in globals().items() if v is arg and not n.startswith('_')]
return results[0] if len(results) is 1 else results if results else None
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
You can use the first selector.
var header = $('.header:first')
Try it:
git gc --prune=now
git remote prune origin
git pull
A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float. For example:
>>> out1 = 1.2345
>>> out1 = float(str(out1)[0:4])
>>> out1
May not be super efficient but simple and works :)
There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.
Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.
EDIT
To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.
The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.
The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)
The terminal can't do anything until the modem is connected.
When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.
So nostalgic!
The most straight forward solution to determine the rank of a given value is to count the number of values before it. Suppose we have the following values:
10 20 30 30 30 40
30
values are considered 3rd40
values are considered 6th (rank) or 4th (dense rank)Now back to the original question. Here is some sample data which is sorted as described in OP (expected ranks are added on the right):
+------+-----------+------+--------+ +------+------------+
| id | firstname | age | gender | | rank | dense_rank |
+------+-----------+------+--------+ +------+------------+
| 11 | Emily | 20 | F | | 1 | 1 |
| 3 | Grace | 25 | F | | 2 | 2 |
| 20 | Jill | 25 | F | | 2 | 2 |
| 10 | Megan | 26 | F | | 4 | 3 |
| 8 | Lucy | 27 | F | | 5 | 4 |
| 6 | Sarah | 30 | F | | 6 | 5 |
| 9 | Zoe | 30 | F | | 6 | 5 |
| 14 | Kate | 35 | F | | 8 | 6 |
| 4 | Harry | 20 | M | | 1 | 1 |
| 12 | Peter | 20 | M | | 1 | 1 |
| 13 | John | 21 | M | | 3 | 2 |
| 16 | Cole | 25 | M | | 4 | 3 |
| 17 | Dennis | 27 | M | | 5 | 4 |
| 5 | Scott | 30 | M | | 6 | 5 |
| 7 | Tony | 30 | M | | 6 | 5 |
| 2 | Matt | 31 | M | | 8 | 6 |
| 15 | James | 32 | M | | 9 | 7 |
| 1 | Adams | 33 | M | | 10 | 8 |
| 18 | Smith | 35 | M | | 11 | 9 |
| 19 | Zack | 35 | M | | 11 | 9 |
+------+-----------+------+--------+ +------+------------+
To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age)
for Sarah, you can use this query:
SELECT COUNT(id) + 1 AS rank, COUNT(DISTINCT age) + 1 AS dense_rank
FROM testdata
WHERE gender = (SELECT gender FROM testdata WHERE id = 6)
AND age < (SELECT age FROM testdata WHERE id = 6)
+------+------------+
| rank | dense_rank |
+------+------------+
| 6 | 5 |
+------+------------+
To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age)
for All rows you can use this query:
SELECT testdata.id, COUNT(lesser.id) + 1 AS rank, COUNT(DISTINCT lesser.age) + 1 AS dense_rank
FROM testdata
LEFT JOIN testdata AS lesser ON lesser.age < testdata.age AND lesser.gender = testdata.gender
GROUP BY testdata.id
And here is the result (joined values are added on right):
+------+------+------------+ +-----------+-----+--------+
| id | rank | dense_rank | | firstname | age | gender |
+------+------+------------+ +-----------+-----+--------+
| 11 | 1 | 1 | | Emily | 20 | F |
| 3 | 2 | 2 | | Grace | 25 | F |
| 20 | 2 | 2 | | Jill | 25 | F |
| 10 | 4 | 3 | | Megan | 26 | F |
| 8 | 5 | 4 | | Lucy | 27 | F |
| 6 | 6 | 5 | | Sarah | 30 | F |
| 9 | 6 | 5 | | Zoe | 30 | F |
| 14 | 8 | 6 | | Kate | 35 | F |
| 4 | 1 | 1 | | Harry | 20 | M |
| 12 | 1 | 1 | | Peter | 20 | M |
| 13 | 3 | 2 | | John | 21 | M |
| 16 | 4 | 3 | | Cole | 25 | M |
| 17 | 5 | 4 | | Dennis | 27 | M |
| 5 | 6 | 5 | | Scott | 30 | M |
| 7 | 6 | 5 | | Tony | 30 | M |
| 2 | 8 | 6 | | Matt | 31 | M |
| 15 | 9 | 7 | | James | 32 | M |
| 1 | 10 | 8 | | Adams | 33 | M |
| 18 | 11 | 9 | | Smith | 35 | M |
| 19 | 11 | 9 | | Zack | 35 | M |
+------+------+------------+ +-----------+-----+--------+
Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click
wb_apple.Document.GetElementById("phoneNumber").Focus()
wb_apple.Document.GetElementById("phoneNumber").InnerText = tb_phonenumber.Text
wb_apple.Document.GetElementById("reservationCode").Focus()
wb_apple.Document.GetElementById("reservationCode").InnerText = tb_regcode.Text
'SendKeys.Send("{Tab}{Tab}{Tab}")
'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName("a")
'If Element.OuterHtml.Contains("iReserve.sms.submitButtonLabel") Then
'Element.InvokeMember("click")
'Exit For
' End If
'Next Element
wb_apple.Document.GetElementById("smsPageForm").Focus()
wb_apple.Document.GetElementById("smsPageForm").InvokeMember("submit")
End Sub
You can use set
with the /p
argument:
SET /P variable=[promptString]
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So, simply use something like
set /p Input=Enter some text:
Later you can use that variable as argument to a command:
myCommand %Input%
Be careful though, that if your input might contain spaces it's probably a good idea to quote it:
myCommand "%Input%"
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
Load environment variables from a file you create at runtime.
export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF
... then in the Dockerfile
ADD build /build
RUN /build/test.sh
where test.sh loads MYVAR from env.sh
#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile
As mentioned in a more recent answer, the preferred way is now simply:
const homedir = require('os').homedir();
[Original Answer]: Why not use the USERPROFILE
environment variable on win32?
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
You could do something like this
var option=document.getElementsByName('Gender');
if (!(option[0].checked || option[1].checked)) {
alert("Please Select Your Gender");
return false;
}
To use an identity column in v10,
ALTER TABLE test
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;
For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.
For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.
For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat()
function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
A simple solution for this problem is to use the IsPostBack check on your page load. That will solve this problem.
You can not restore database (or attach) created in the upper version into lower version. The only way is to create a script for all objects and use the script to generate database.
select "Schema and Data" - if you want to Take both the things in to the Backup script file
select Schema Only - if only schema is needed.
Yes, now you have done with the Create Script with Schema and Data of the Database.
This works for me for the iphone 6
/*iPhone 6 Portrait*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : portrait) {
}
/*iPhone 6 landscape*/
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation : landscape) {
}
/*iPhone 6+ Portrait*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : portrait) {
}
/*iPhone 6+ landscape*/
@media only screen and (min-device-width: 414px) and (max-device-width: 736px) and (orientation : landscape) {
}
/*iPhone 6 and iPhone 6+ portrait and landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px){
}
/*iPhone 6 and iPhone 6+ portrait*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : portrait){
}
/*iPhone 6 and iPhone 6+ landscape*/
@media only screen and (max-device-width: 640px), only screen and (max-device-width: 667px), only screen and (max-width: 480px) and (orientation : landscape){
}
e.printStackTrace equivalent in python
In Java, this does the following (docs):
public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream...
This is used like this:
try
{
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}
In Java, the Standard Error stream is unbuffered so that output arrives immediately.
import traceback
import sys
try: # code that may raise an error
pass
except IOError as e: # exception handling
# in Python 2, stderr is also unbuffered
print >> sys.stderr, traceback.format_exc()
# in Python 2, you can also from __future__ import print_function
print(traceback.format_exc(), file=sys.stderr)
# or as the top answer here demonstrates, use:
traceback.print_exc()
# which also uses stderr.
In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:
print(traceback.format_exception(None, # <- type(e) by docs, but ignored
e, e.__traceback__),
file=sys.stderr, flush=True)
Conclusion:
In Python 3, therefore, traceback.print_exc()
, although it uses sys.stderr
by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print
with flush=True
.
You can push all local tags by simply git push --tags
command.
$ git tag # see tag lists
$ git push origin <tag-name> # push a single tag
$ git push --tags # push all local tags
Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}
The correct Angular way to do this is to write a single page app, AJAX in the form template, then populate it dynamically from the model. The model is not populated from the form by default because the model is the single source of truth. Instead Angular will go the other way and try to populate the form from the model.
If you have an app written, this might involve some fairly hefty architectural changes. If you're trying to use Angular to enhance an existing form, rather than constructing an entire single page app from scratch, you can pull the value from the form and store it in the scope at link time using a directive. Angular will then bind the value in the scope back to the form and keep it in sync.
You can use a relatively simple directive to pull the value from the form and load it in to the current scope. Here I've defined an initFromForm directive.
var myApp = angular.module("myApp", ['initFromForm']);
angular.module('initFromForm', [])
.directive("initFromForm", function ($parse) {
return {
link: function (scope, element, attrs) {
var attr = attrs.initFromForm || attrs.ngModel || element.attrs('name'),
val = attrs.value;
if (attrs.type === "number") {val = parseInt(val)}
$parse(attr).assign(scope, val);
}
};
});
You can see I've defined a couple of fallbacks to get a model name. You can use this directive in conjunction with the ngModel directive, or bind to something other than $scope if you prefer.
Use it like this:
<input name="test" ng-model="toaster.test" value="hello" init-from-form />
{{toaster.test}}
Note this will also work with textareas, and select dropdowns.
<textarea name="test" ng-model="toaster.test" init-from-form>hello</textarea>
{{toaster.test}}
I don't fully understand but, can use pandas
for getting times in right format:
>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>>
And:
>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']
But it's storing strings but easy to convert:
>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
I would state it with the following analogy:
+-----------------------------+-------+-----------+
| Domain | Meta | Concrete |
+-----------------------------+-------+-----------+
| Docker | Image | Container |
| Object oriented programming | Class | Object |
+-----------------------------+-------+-----------+
Usually you make the thing you don't want duplicates of unique, and allow the database itself to refuse the insert.
Otherwise, you can use INSERT INTO, see How to avoid duplicates in INSERT INTO SELECT query in SQL Server?
public static Bitmap overlayBitmapToCenter(Bitmap bitmap1, Bitmap bitmap2) {
int bitmap1Width = bitmap1.getWidth();
int bitmap1Height = bitmap1.getHeight();
int bitmap2Width = bitmap2.getWidth();
int bitmap2Height = bitmap2.getHeight();
float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);
Bitmap overlayBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
Canvas canvas = new Canvas(overlayBitmap);
canvas.drawBitmap(bitmap1, new Matrix(), null);
canvas.drawBitmap(bitmap2, marginLeft, marginTop, null);
return overlayBitmap;
}
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:
Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.
<div id="container">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
#container { width: 600px; }
#container p { float: left; width: 300px; /* possibly also height: 300px; */ }
You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want two columns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:
<div id="container">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<div class="clear"></div>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<div class="clear"></div>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
/* in addition to the above CSS */
.clear { clear: both; height: 0; }
More advanced, but it can be done.
<div id="container">
<div class="contentColumn">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
</div>
<div class="contentColumn">
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
</div>
.contentColumn { width: 300px; float: left; }
#container { width: 600px; }
When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.
Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.
You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.