To avoid all the Oracle mess of not knowing where it is looking for the TNSNAMES.ORA (I have the added confusion of multiple Oracle versions and 32/64 bit), you can copy the setting from your existing TNSNAMES.ORA to your own config file and use that for your connection.
Say you're happy with the 'DSDSDS' reference in TNSNAMES.ORA which maps to something like:
DSDSDS=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)))
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=DSDSDSHost)(Port=4521)))(CONNECT_DATA=(SERVICE_NAME=DSDSDSService)));User Id=UNUNUN;Password=PWPWPW;";
If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability
It's really easy to create folders. Actually it's just creating keys.
You can see my below code i was creating a folder with utc_time as name.
Do remember ends the key with '/' like below, this indicates it's a key:
Key='folder1/' + utc_time + '/'
client = boto3.client('s3')
utc_timestamp = time.time()
def lambda_handler(event, context):
UTC_FORMAT = '%Y%m%d'
utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
utc_time = utc_time.strftime(UTC_FORMAT)
print 'start to create folder for => ' + utc_time
putResponse = client.put_object(Bucket='mybucketName',
Key='folder1/' + utc_time + '/')
print putResponse
The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:
It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: https://github.com/twbs/bootstrap/pull/10465. This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.
def infinity():
i=0
while True:
i+=1
yield i
for i in infinity():
if there_is_a_reason_to_break(i):
break
I tried the methods mentioned in some other answers, but they look like workarounds to me. Using Firefox Add-on RESTclient to send HTTP POST requests with parameters is not straightforward in my opinion, at least for the version I'm currently using, 2.0.1.
Instead, try using other free open source tools, such as Apache JMeter. It is simple and straightforward (see the screenshot as below)
overflow:auto
to container div.float:left
to the first element.position:relative; top: 0.2em; left: 24em
to the second element (Top and left values can vary according to you).First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
Razz's answer is good if you're willing to rewrite what you have done.
Was in the same trouble and worked it out with the following:
/**_x000D_
* The problem: https://github.com/twbs/bootstrap/issues/9881_x000D_
* _x000D_
* This script enhances jQuery's methods: show and hide dynamically._x000D_
* If the element was hidden by bootstrap's css class 'hide', remove it first._x000D_
* Do similar in overriding the method 'hide'._x000D_
*/_x000D_
!function($) {_x000D_
"use strict";_x000D_
_x000D_
var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide};_x000D_
$.fn.extend({_x000D_
show: function() {_x000D_
this.each(function(index) {_x000D_
var $element = $(this);_x000D_
if ($element.hasClass('hide')) {_x000D_
$element.removeClass('hide');_x000D_
}_x000D_
});_x000D_
return oldShowHide.show.call(this);_x000D_
},_x000D_
hide: function() {_x000D_
this.each(function(index) {_x000D_
var $element = $(this);_x000D_
if ($element.hasClass('show')) {_x000D_
$element.removeClass('show');_x000D_
}_x000D_
});_x000D_
return oldShowHide.hide.call(this);_x000D_
}_x000D_
});_x000D_
}(window.jQuery);
_x000D_
Throw it away when Bootstrap comes with a fix for this problem.
Can I offer an alternative solution?
I had this same issue, and fade didn't work because it faded the entire element, not just the background. In my case the element was body, so I only wanted to fade the background.
An elegant way to tackle this is to class the element and use CSS3 transition for the background.
transition: background 0.5s linear;
When you change the background, either with toggleClass or with your code, $("#large-img").css('background-image', 'url('+$img+')');
it will fade as defined by the class.
Our array of objects
var someData = [
{firstName: "Max", lastName: "Mustermann", age: 40},
{firstName: "Hagbard", lastName: "Celine", age: 44},
{firstName: "Karl", lastName: "Koch", age: 42},
];
with for...in
var employees = {
accounting: []
};
for(var i in someData) {
var item = someData[i];
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
or with Array.prototype.map()
, which is much cleaner:
var employees = {
accounting: []
};
someData.map(function(item) {
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
Installing babel
globally solves this issue:
npm install -g @babel/core @babel/cli
However, it is not encourage to install dependencies globally because they won't have their versions managed on a per-project basis.
You should install your dependencies locally, as suggested on babel
's documentation:
npm install --save-dev @babel/core @babel/cli
The downside is that this gives you no fast/convenient way to invoke local binaries interactively (in this case babel
). npx
gives you a great solution:
npx babel --version
This will run your local installation of babel
. Additionally, if you want to avoid typing npx
, you can configure the shell auto fallback, and then just run:
babel --version
Note: it is important to create a file .babelrc
, at your project's root, in which you specify your babel configuration. As a starting point you can use env-preset
to transpile to ES2015+:
npm install @babel/preset-env --save-dev
In order to enable the preset you have to define it in your .babelrc file, like this:
{
"presets": ["@babel/preset-env"]
}
For the sake of future readers. My problem was that I was specifying an incompatible openssl library to build my program through CMAKE. Projects were generated but build started failing with this error without any other useful information or error. Verbose cmake/compilation logs didn't help either.
My take away lesson is that cross check the incompatibilities in case your program has dependencies on the any other third party library.
There is no need to install virtualenv. Just create a workfolder and open your editor in it. Assuming you are using vscode,
$mkdir Directory && cd Directory
$code .
It is the best way to avoid breaking Ubuntu/linux dependencies by messing around with environments. In case anything goes wrong, you can always delete that folder and begin afresh. Otherwise, messing up with the ubuntu/linux python environments could mess up system apps/OS (including the terminal). Then you can press shift+P and type python:select interpreter. Choose any version above 3. After that you can do
$pip3 -v
It will display the pip version. You can then use it for installations as
$pip3 install Library
For a quick fix, I like this:
let var:CGFloat = (UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436) ? <iPhoneX> : <AllOthers>
I would wrap the map inside a static object, and put the map initialisation code in the constructor of this object, this way you are sure the map is created before the initialisation code is executed.
32-bit JVMs which expect to have a single large chunk of memory and use raw pointers cannot use more than 4 Gb (since that is the 32 bit limit which also applies to pointers). This includes Sun and - I'm pretty sure - also IBM implementations. I do not know if e.g. JRockit or others have a large memory option with their 32-bit implementations.
If you expect to be hitting this limit you should strongly consider starting a parallel track validating a 64-bit JVM for your production environment so you have that ready for when the 32-bit environment breaks down. Otherwise you will have to do that work under pressure, which is never nice.
Edit 2014-05-15: Oracle FAQ:
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.
(http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit)
Do not bind to element id, just use the 'previous' input element to clear.
CSS:
.clear-input > span {
position: absolute;
right: 24px;
top: 10px;
height: 14px;
margin: auto;
font-size: 14px;
cursor: pointer;
color: #AAA;
}
Javascript:
function $(document).ready(function() {
$(".clear-input>span").click(function(){
// Clear the input field before this clear button
// and give it focus.
$(this).prev().val('').focus();
});
});
HTML Markup, use as much as you like:
<div class="clear-input">
Pizza: <input type="text" class="form-control">
<span class="glyphicon glyphicon-remove-circle"></span>
</div>
<div class="clear-input">
Pasta: <input type="text" class="form-control">
<span class="glyphicon glyphicon-remove-circle"></span>
</div>
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
You can use the CheckedChanged event for all your RadioButtons. Sender
will be the unchecked and checked RadioButtons.
Environment variables are accessed through os.environ
import os
print(os.environ['HOME'])
Or you can see a list of all the environment variables using:
os.environ
As sometimes you might need to see a complete list!
# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
Python default installation on Windows is C:\Python
. If you want to find out while running python you can do:
import sys
print(sys.prefix)
I want to be clear that the following code is not good practice. You can use GOTO Label:
For Each I As Item In Items
If I = x Then
'Move to next item
GOTO Label1
End If
' Do something
Label1:
Next
list multiplication works.
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"":'',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as
json.property_name
If your binary search tree is a red black tree, or you intend to any kind of "tree rotation" operations, duplicate nodes will cause problems. Imagine your tree rule is this:
left < root <= right
Now imagine a simple tree whose root is 5, left child is nil, and right child is 5. If you do a left rotation on the root you end up with a 5 in the left child and a 5 in the root with the right child being nil. Now something in the left tree is equal to the root, but your rule above assumed left < root.
I spent hours trying to figure out why my red/black trees would occasionally traverse out of order, the problem was what I described above. Hopefully somebody reads this and saves themselves hours of debugging in the future!
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
In your Component you can add .class to your host element if you would have some general styles that you want to apply.
export class MyComponent{
@HostBinding('class') classes = 'classA classB';
You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.
This answer works well with Bootstrap v3.x . For version 4.x see @User comment below
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
var $draggable = $(this);_x000D_
var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
$("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
$draggable.closest(".modal-dialog").offset({_x000D_
"left": mousemoveEvt.pageX - x,_x000D_
"top": mousemoveEvt.pageY - y_x000D_
});_x000D_
});_x000D_
$("body").one("mouseup", function() {_x000D_
$("body").off("mousemove.draggable");_x000D_
});_x000D_
$draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
$("body").off("mousemove.draggable");_x000D_
});_x000D_
});
_x000D_
.modal-header {_x000D_
cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>One fine body…</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div><!-- /.modal-content -->_x000D_
</div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
This is common greatest-n-per-group problem, which already has well tested and highly optimized solutions. Personally I prefer the left join solution by Bill Karwin (the original post with lots of other solutions).
Note that bunch of solutions to this common problem can surprisingly be found in the one of most official sources, MySQL manual! See Examples of Common Queries :: The Rows Holding the Group-wise Maximum of a Certain Column.
Here is an answer by way of example:
In order to make sure data loggers are online a cron
script runs every 15 minutes that looks like this:
#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
echo "SUBJECT: SOLAR is not responding to ping" | ssmtp [email protected]
echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
echo "SUBJECT: OUTSIDE is not responding to ping" | ssmtp [email protected]
echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
echo "OUTSIDE is up"
fi
#
...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage
FYI, using &>/dev/null
redirects all output from the command, including errors, to /dev/null
(The conditional only requires the exit status
of the ping
command)
Also FYI, note that since cron
jobs run as root
there is no need to use sudo ping
in a cron
script.
Using the trick
Attribute VB_PredeclaredId = True
I found another more compact way:
Option Explicit
Option Base 0
Option Compare Binary
Private v_cBox As ComboBox
'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
If Me Is ComboBoxExt_c Then
Set New_ = New ComboBoxExt_c
Call New_.New_(cBox)
Else
Set v_cBox = cBox
End If
End Function
As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.
I was running on the same problem, wampmysqld64 did not start, so I checked the Mysql log which you should find it inside the main wamp64 folder, and I found all the details on why is not working. on my computer I found another mysql instance is running so it prevents the wampmysqld64 to start. I stopped the other instance, and everything works fine after.
When I switched careers out of Finance, I took 9 months off to study C++ full-time out of a book by Ivor Horton. I had a lot of support from my best friend, who is a guru, and I had been programming as a hobby since high school (I was 36 at the time).
It's not just the syntax that's an issue. The idea of things like pointers, passing by reference, multi-tiered architectures, struct's vs classes, etc., these all take time to understand and learn to use. And you're adding to that the .Net framework, which is huge and constantly evolving, and SQL, which is a totally different skill set than C#. You also haven't mentioned various subsets of the framework that are becoming more widely used, like WPF, WCF, WF, etc.
You're an academic so you can definitely do it, but it's going to take serious effort for a long time, and you definitely will need some projects to work on and learn from. Good luck to you.
If you'd like to use Code Behind, may I suggest the following solution for an asp:button -
ASPX Page
<asp:Button ID="btnRecover" runat="server" Text="Recover" OnClick="btnRecover_Click" />
Code Behind
protected void btnRecover_Click(object sender, EventArgs e)
{
var recoveryId = Guid.Parse(lbRecovery.SelectedValue);
var url = string.Format("{0}?RecoveryId={1}", @"../Recovery.aspx", vehicleId);
// Response.Redirect(url); // Old way
Response.Write("<script> window.open( '" + url + "','_blank' ); </script>");
Response.End();
}
a more modern approach would be to use css flex-box.
div {_x000D_
height: 50px;_x000D_
background: grey;_x000D_
display: flex;_x000D_
align-items: center_x000D_
}
_x000D_
<div>_x000D_
<label for='name'>Name:</label>_x000D_
<input type='text' id='name' />_x000D_
</div>
_x000D_
a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...
div {_x000D_
display: flex;_x000D_
align-items: center_x000D_
}_x000D_
_x000D_
* {_x000D_
margin: 10px_x000D_
}_x000D_
_x000D_
label {_x000D_
align-self: flex-start_x000D_
}
_x000D_
<div>_x000D_
<img src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=50" />_x000D_
<label>Text</label>_x000D_
<input placeholder="Text" type="text" />_x000D_
</div>
_x000D_
its also super easy to center horizontally and vertically:
div {_x000D_
position:absolute;_x000D_
top:0;left:0;right:0;bottom:0;_x000D_
background: grey;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content:center_x000D_
}
_x000D_
<div>_x000D_
<label for='name'>Name:</label>_x000D_
<input type='text' id='name' />_x000D_
</div>
_x000D_
I was getting the same error, but performing a null check did not seem to help.
The solution I found was to wrap my function inside an event listener for the whole document to check when the DOM finished loading.
document.addEventListener('DOMContentLoaded', function () {
el.addEventListener('click', swapper, false);
});
I think this is because I am using a framework (Angular) that is changing my HTML classes and ID's dynamically.
With SQL 2012 and later, you could use TRY_CAST
/TRY_CONVERT
to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL
-- note though that this will match scientific notation too (1+E34). (If you use decimal
, then scientific notation won't match)
Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.
Use the following code:
df.column_name = df.column_name.astype('str')
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).
In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.
This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)
There are two approaches explained in the great tutorial be Alex Lockwood: http://www.androiddesignpatterns.com/2016/08/coloring-buttons-with-themeoverlays-background-tints.html:
Approach #1: Modifying the button’s background color w/ a ThemeOverlay
<!-- res/values/themes.xml -->
<style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/googred500</item>
</style>
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/RedButtonLightTheme"/>
Approach #2: Setting the AppCompatButton’s background tint
<!-- res/color/btn_colored_background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Disabled state. -->
<item android:state_enabled="false"
android:color="?attr/colorButtonNormal"
android:alpha="?android:attr/disabledAlpha"/>
<!-- Enabled state. -->
<item android:color="?attr/colorAccent"/>
</selector>
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="@color/btn_colored_background_tint"/>
Run this query from PostgreSQL:
SELECT version();
I think this code gets the same and is easier to read.
SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE date >= (SELECT date from mytable)
OR date <= (SELECT date from mytable);
I have examined all the above answer's, We just need to implement two things to work it as expected.
Step - 1: Add the (click) event in the anchor tag in the HTML page and remove the href=" " as its explicitly for navigating to external links, Instead use routerLink = " " which helps in navigating views.
<ul>
<li><a routerLink="" (click)="hitAnchor1($event)"><p>Click One</p></a></li>
<li><a routerLink="" (click)="hitAnchor2($event)"><p>Click Two</p></a></li>
</ul>
Step - 2: Call the above function to attach the click event to anchor tags (coming from ajax) in the .ts file,
hitAnchor1(e){
console.log("Events", e);
alert("You have clicked the anchor-1 tag");
}
hitAnchor2(e){
console.log("Events", e);
alert("You have clicked the anchor-2 tag");
}
That's all. It work's as expected. I created the example below, You can have a look:-
New is always used to allocate dynamic memory, which then has to be freed.
By doing the first option, that memory will be automagically freed when scope is lost.
Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.
Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;
The problem may lie in you don't have enabled openssl extention in your php.ini file
go to your php.ini file end remove ;
in line where extension=openssl
is
Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it
I've made for myself a small drawing that represents the following code snippet:
var Cat = function() {}
var tom = new Cat()
I have a classical OO background, so it was helpful to represent the hierarchy in this manner. To help you read this diagram, treat the rectangles in the image as JavaScript objects. And yes, functions are also objects. ;)
Objects in JavaScript have properties and __proto__
is just one of them.
The idea behind this property is to point to the ancestor object in the (inheritance) hierarchy.
The root object in JavaScript is Object.prototype
and all other objects are descendants of this one. The __proto__
property of the root object is null
, which represents the end of inheritance chain.
You'll notice that prototype
is a property of functions. Cat
is a function, but also Function
and Object
are (native) functions. tom
is not a function, thus it does not have this property.
The idea behind this property is to point to an object which will be used in the construction, i.e. when you call the new
operator on that function.
Note that prototype objects (yellow rectangles) have another property called
constructor
which points back to the respective function object. For brevity reasons this was not depicted.
Indeed, when we create the tom
object with new Cat()
, the created object will have the __proto__
property set to the prototype
object of the constructor function.
In the end, let us play with this diagram a bit. The following statements are true:
tom.__proto__
property points to the same object as Cat.prototype
.
Cat.__proto__
points to the Function.prototype
object, just like Function.__proto__
and Object.__proto__
do.
Cat.prototype.__proto__
and tom.__proto__.__proto__
point to the same object and that is Object.prototype
.
Cheers!
If you are stuck to an earlier version of Java than 8 but already using AWS SDK for Java, you can use com.amazonaws.util.Base64.
A simple and clean way: use np.argwhere
to group the indices by element, rather than dimension as in np.nonzero(a)
(i.e., np.argwhere
returns a row for each non-zero element).
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
[6],
[7],
[8],
[9]])
np.argwhere(a)
is the same as np.transpose(np.nonzero(a))
.
Note: You cannot use a(np.argwhere(a>4))
to get the corresponding values in a
. The recommended way is to use a[(a>4).astype(bool)]
or a[(a>4) != 0]
rather than a[np.nonzero(a>4)]
as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)]
and a[(a>4) != 0]
can be simplified to a[a>4]
.
Another example:
>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([ 5, -15, -8, -5, 10])
>>> a > 4
array([ True, False, False, False, True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10, -3, 0, 15],
[-10, -30, -23, -20, -5],
[ -3, -23, -16, -13, 2],
[ 0, -20, -13, -10, 5],
[ 15, -5, 2, 5, 20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
[0, 4],
[3, 4],
[4, 0],
[4, 3],
[4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4
You can easily invoke the push method via context in v4:
this.context.router.push(this.props.exitPath);
where context is:
static contextTypes = {
router: React.PropTypes.object,
};
Use the Apache Commons CLI library commandline.getArgs() to get arg1, arg2, arg3, and arg4. Here is some code:
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Option.Builder;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
public static void main(String[] parameters)
{
CommandLine commandLine;
Option option_A = Option.builder("A")
.required(true)
.desc("The A option")
.longOpt("opt3")
.build();
Option option_r = Option.builder("r")
.required(true)
.desc("The r option")
.longOpt("opt1")
.build();
Option option_S = Option.builder("S")
.required(true)
.desc("The S option")
.longOpt("opt2")
.build();
Option option_test = Option.builder()
.required(true)
.desc("The test option")
.longOpt("test")
.build();
Options options = new Options();
CommandLineParser parser = new DefaultParser();
String[] testArgs =
{ "-r", "opt1", "-S", "opt2", "arg1", "arg2",
"arg3", "arg4", "--test", "-A", "opt3", };
options.addOption(option_A);
options.addOption(option_r);
options.addOption(option_S);
options.addOption(option_test);
try
{
commandLine = parser.parse(options, testArgs);
if (commandLine.hasOption("A"))
{
System.out.print("Option A is present. The value is: ");
System.out.println(commandLine.getOptionValue("A"));
}
if (commandLine.hasOption("r"))
{
System.out.print("Option r is present. The value is: ");
System.out.println(commandLine.getOptionValue("r"));
}
if (commandLine.hasOption("S"))
{
System.out.print("Option S is present. The value is: ");
System.out.println(commandLine.getOptionValue("S"));
}
if (commandLine.hasOption("test"))
{
System.out.println("Option test is present. This is a flag option.");
}
{
String[] remainder = commandLine.getArgs();
System.out.print("Remaining arguments: ");
for (String argument : remainder)
{
System.out.print(argument);
System.out.print(" ");
}
System.out.println();
}
}
catch (ParseException exception)
{
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
}
}
As requested, I have transfered my comment to an answer so people can upvote it:
This works 90% of the time for iOS 13:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover, user-scalable=no, shrink-to-fit=no" />
and
<meta name="HandheldFriendly" content="true">
Definitely Method A because its pooled and thread safe.
If you are using httpclient 4.x, the connection manager is called ThreadSafeClientConnManager. See this link for further details (scroll down to "Pooling connection manager"). For example:
HttpParams params = new BasicHttpParams();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, registry);
HttpClient client = new DefaultHttpClient(cm, params);
You're going to be disappointed: %userprofile%
You can use other terminals, though. Powershell, which I believe you can get on XP and later (and comes preinstalled with Win7), allows you to use ~
for home directory.
Yep, Oracle has temporary tables. Here is a link to an AskTom article describing them and here is the official oracle CREATE TABLE documentation.
However, in Oracle, only the data in a temporary table is temporary. The table is a regular object visible to other sessions. It is a bad practice to frequently create and drop temporary tables in Oracle.
CREATE GLOBAL TEMPORARY TABLE today_sales(order_id NUMBER)
ON COMMIT PRESERVE ROWS;
Oracle 18c added private temporary tables, which are single-session in-memory objects. See the documentation for more details. Private temporary tables can be dynamically created and dropped.
CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;
Temporary tables can be useful but they are commonly abused in Oracle. They can often be avoided by combining multiple steps into a single SQL statement using inline views.
There's a pause
command that does just that, though it's not specifically the enter key.
If you really want to wait for only the enter key, you can use the set
command to ask for user input with a dummy variable, something like:
set /p DUMMY=Hit ENTER to continue...
If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.
Working example: http://jsfiddle.net/d9Q5H/1/
HTML:
<div class="image-blurred-edge"></div>
CSS
.image-blurred-edge {
background-image: url('http://lorempixel.com/200/200/city/9');
width: 200px;
height: 200px;
/* you need to match the shadow color to your background or image border for the desired effect*/
box-shadow: 0 0 8px 8px white inset;
}
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
Could do this, but then the user has to separate the numbers by a space:
#include "stdio.h"
int main()
{
int minx, x, y, z;
printf("Enter four ints: ");
scanf( "%i %i %i %i", &minx, &x, &y, &z);
printf("You wrote: %i %i %i %i", minx, x, y, z);
}
jQuery has the inArray
function:
There is no such thing as "SOAP protocol". SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
zlists = [[0] * i for i in range(10)]
zlists[0]
is a list of 0 zeroes, zlists[1]
is a list of 1 zero, zlists[2]
is a list of 2 zeroes, etc.
Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .
the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .
Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.
One more that's not on his list:
[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816
But if all you want to do is subtract, why bother changing the input to base 10?
[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$
The dc
command is "desk calc". It will also take input from stdin, like bc
, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.
In the commands above we've got the following:
16i
-- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.BFCA3000
-- your initial number17FF
-- a random hex number I picked to subtract from your initial number-
-- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stackp
-- print the last item on the stack. This doesn't change the stack, so...10o
-- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".p
-- print the last item on the stack again ... this time in hex.You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.
jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:
public class MaxAttribute : ValidationAttribute, IClientValidatable
{
private readonly int maxValue;
public MaxAttribute(int maxValue)
{
this.maxValue = maxValue;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = ErrorMessageString, maxValue;
rule.ValidationType = "max";
rule.ValidationParameters.Add("max", maxValue);
yield return rule;
}
public override bool IsValid(object value)
{
return (int)value <= maxValue;
}
}
Adapter:
$.validator.unobtrusive.adapters.add(
'max',
['max'],
function (options) {
options.rules['max'] = parseInt(options.params['max'], 10);
options.messages['max'] = options.message;
});
Min attribute would be very similar.
I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.
I managed to get it to work by adding both the height
and min-height
properties to the CSS class.
The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:
.flex-container {
display: flex;
flex-direction: column;
min-height: 100px;
height: 100px;
}
Hope this helps!
var obj={_x000D_
name:"SanD",_x000D_
age:"27"_x000D_
}_x000D_
Object.keys(obj).forEach((key)=>console.log(key,obj[key]));
_x000D_
To loop through JavaScript Object we can use forEach and to optimize code we can use arrow function
cat * | grep -c string
Addition to Alex' answer:
$(function() {
$('input[type="submit"]').prop('disabled', true);
$('#check').on('input', function(e) {
if(this.value.length === 6) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
});
<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />
But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.
By definition, the put
command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).
The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null
if none present), so you can determine what was there and maintain a reference if necessary.
More information here: HashMap Doc
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).
document.querySelector('input[name="gender"]:checked').value
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
I just added an @ symbol and it started working. Like this: @$product->save();
The proposed solutions suffer from the fact that they either explicitly iterate over a collection or stuff the collection into a function. It is more natural to stick with the usual idioms of Scala and put the index inside the usual map- or foreach-methods. This can be done using memoizing. The resulting code might look like
myIterable map (doIndexed(someFunction))
Here is a way to achieve this purpose. Consider the following utility:
object TraversableUtil {
class IndexMemoizingFunction[A, B](f: (Int, A) => B) extends Function1[A, B] {
private var index = 0
override def apply(a: A): B = {
val ret = f(index, a)
index += 1
ret
}
}
def doIndexed[A, B](f: (Int, A) => B): A => B = {
new IndexMemoizingFunction(f)
}
}
This is already all you need. You can apply this for instance as follows:
import TraversableUtil._
List('a','b','c').map(doIndexed((i, char) => char + i))
which results in the list
List(97, 99, 101)
This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. Enjoy!
If you use Spring Boot 2.0.0 use:
server.servlet.context-path
with bootstrap use class input-md = medium, input-lg = large, for more info see https://getbootstrap.com/docs/3.3/css/#forms-control-sizes
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
Per the specification, the JSON grammar's char production can take the following values:
"
-or-\
-or-control-character\"
\\
\/
\b
\f
\n
\r
\t
\u
four-hex-digitsNewlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n
and \r
you require.
The JSONLint tool confirms that your JSON is invalid.
And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.
To remove trailing white space while ignoring empty lines I use positive look-behind:
(?<=\S)\s+$
The look-behind is the way go to exclude the non-whitespace (\S) from the match.
To understand why jQuery is so popular, it's important to understand where we're coming from!
About a decade ago, top browsers were IE6, Netscape 8 and Firefox 1.5. Back in those days, there were little cross-browser ways to select an element from the DOM besides Document.getElementById()
.
So, when jQuery was released back in 2006, it was pretty revolutionary. Back then, jQuery set the standard for how to easily select / change HTML elements and trigger events, because its flexibility and browser support were unprecedented.
Now, more than a decade later, a lot of features that made jQuery so popular have become included in the javaScript standard:
$()
, you can now now use Document.querySelectorAll()
$el.on()
, you can now use EventTarget.addEventListener()
$el.toggleClass()
, you can now use Element.classList.toggle()
These weren't generally available back in 2005. The fact that they are today obviously begs the question of why we should use jQuery at all. And indeed, people are increasingly wondering whether we should use jQuery at all.
So, if you think you understand JavaScript well enough to do without jQuery, please do! Don't feel forced to use jQuery, just because so many others are doing it!
Why not use properly formulated geospatial queries???
Here is the SQL server reference page on the STContains geospatial function:
or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:
DECLARE @CurrentLocation geography;
SET @CurrentLocation = geography::Point(12.822222, 80.222222, 4326)
SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km
There should be similar functionality for almost any database out there.
If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using
I figured this one out. I know this will help someone someday.
How to Vertically & Horizontally Center a Div Over a Relatively Positioned Image
The key was a 3rd wrapper. I would vote up any answer that uses less wrappers.
HTML
<div class="wrapper">
<img src="my-slide.jpg">
<div class="outer-wrapper">
<div class="table-wrapper">
<div class="table-cell-wrapper">
<h1>My Title</h1>
<p>Subtitle</p>
</div>
</div>
</div>
</div>
CSS
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
}
ul {
width: 100%;
height: 100%;
list-style-position: outside;
margin: 0; padding: 0;
}
li {
width: 100%;
display: table;
}
img {
width: 100%;
height: 100%;
}
.outer-wrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
margin: 0; padding: 0;
}
.table-wrapper {
width: 100%;
height: 100%;
display: table;
vertical-align: middle;
text-align: center;
}
.table-cell-wrapper {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
You can see the working jsFiddle here.
One instance when you may consider uuid1()
rather than uuid4()
is when UUIDs are produced on separate machines, for example when multiple online transactions are process on several machines for scaling purposes.
In such a situation, the risks of having collisions due to poor choices in the way the pseudo-random number generators are initialized, for example, and also the potentially higher numbers of UUIDs produced render more likely the possibility of creating duplicate IDs.
Another interest of uuid1()
, in that case is that the machine where each GUID was initially produced is implicitly recorded (in the "node" part of UUID). This and the time info, may help if only with debugging.
Another way to control this setting is by using an undocumented registry key AutoDetect=0 mentioned on this blog post:
Registry Key :
HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\
DWORD
AutoDetect
= 0 or 1
So the .reg file to turn it off would look like:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
"AutoDetect"=dword:00000000
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
If you get some compile errors for example:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
.
private void methodThatRequiresAPI11() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888; // API Level 1
options.inSampleSize = 8; // API Level 1
options.inBitmap = bitmap; // **API Level 11**
//...
}
You get compile error:
Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap
Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi
that can fix this very easily. Add it before the method that is enclosing the problematic declaration:
@TargetApi
private void methodThatRequiresAPI11() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888; // API Level 1
options.inSampleSize = 8; // API Level 1
// This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime.
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
options.inBitmap = bitmap; // **API Level 11**
//...
}
}
No compile errors now and it will run !
EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.
Add a class:
.com_box:after {
content: '';
position: absolute;
left: 18px;
top: 50px;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #000;
clear: both;
}
Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/
You can change axis text and label size with arguments axis.text=
and axis.title=
in function theme()
. If you need, for example, change only x axis title size, then use axis.title.x=
.
g+theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"))
There is good examples about setting of different theme()
parameters in ggplot2 page.
If you're looking to access the current page from within your functions.php file (so, before the loop, before $post
is populated, before $wp_query
is initialized, etc...) you really have no choice but to access the server variables themselves and extract the requested page from the query string.
$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )
Note that this is a "dumb" solution. It doesn't know, for instance that the page with the slug 'coming-soon' is also p=6
. And it assumes that your permalink settings are set to pagename
(which they should be anyway!).
Still, can be a useful little trick if you have a controlled scenario. I'm using this in a situation where I wish to redirect non-logged in visitors to a "coming soon" page; but I have to make sure that I'm not throwing them into the dreaded "redirect loop", so I need to exclude the "coming soon" page from this rule:
global $pagenow;
if (
! is_admin() &&
'wp-login.php' != $pagenow &&
'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
! is_user_logged_in()
){
wp_safe_redirect( 'coming-soon' );
}
Google has updated the Virtual Device targeting API 23. It now comes with Google Play Services 9.0.80. So if you are using Google Maps API V 2.0 (I'm using play-services-maps:9.0.0 and play-services-location.9.0.0) no workaround necessary. It just works!
On my Windows 7 machine I have the following environment variables:
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07
M2_HOME=C:\apache-maven-3.0.3
On my PATH
variable, I have (among others) the following:
I tried doing what you've done with %M2%
having the nested %M2_HOME%
and it also works.
Below are the steps you can try it out to resolve the issue: -
parent="android:Theme.Holo.Light"
instead.
parent="android:Theme.AppCompat.Light"
But option 2 will require minimum sdk version 14.
Hope this will help !
Summved
It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end.
Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants.
Wikipedia is a reasonably good source of more information.
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
htons
is host-to-network short
This means it works on 16-bit short integers. i.e. 2 bytes.
This function swaps the endianness of a short.
Your number starts out at:
0001 0011 1000 1001 = 5001
When the endianness is changed, it swaps the two bytes:
1000 1001 0001 0011 = 35091
The obvious answer, of course, is not to do the unchecked cast.
If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings
annotation. According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.
Example:
@SuppressWarnings("unchecked")
Map<String, String> myMap = (Map<String, String>) deserializeMap();
There is no way to determine whether the Map
really should have the generic parameters <String, String>
. You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException
). This is why the code generates a warning, because the compiler can't possibly know whether is safe.
Use the power of Python and lean on one of the best libraries around: requests
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
Include the custom error page after changing the header.
Add the following CSS;
.modal .modal-dialog .modal-content{ background-color: #d4c484; }
<div class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
...
...
git checkout old_branch
git branch new_branch
This will give you a new branch "new_branch" with the same state as "old_branch".
This command can be combined to the following:
git checkout -b new_branch old_branch
You have use to repeat-y
as style="background-repeat:repeat-y;width: 200px;"
instead of style="repeat-y"
.
Try this inside the image tag or you can use the below css for the div
.div_backgrndimg
{
background-repeat: repeat-y;
background-image: url("/image/layout/lotus-dreapta.png");
width:200px;
}
Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
Or install syswin package, which includes a port of su for cygwin: http://sourceforge.net/p/manufacture/wiki/syswin-su/
I added the .resx file via Visual Studio. This created a designer.cs
file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.
/// <summary>
/// Looks up a localized string similar to When creating a Commissioning change request, you must select valid Assignees, a Type, a Component, and at least one (1) affected unit..
/// </summary>
public static string MyErrorMessage {
get {
return ResourceManager.GetString("MyErrorMessage", resourceCulture);
}
}
That way, I was able to simply do:
string message = Errors.MyErrorMessage;
Where Errors
is the Errors.resx
file created through Visual Studio and MyErrorMessage
is the key.
In Xcode, select Target -> Capabilities, and check "Outgoing Connections (Client)" to enable App Sandbox.
This works for me
.print+.print {
page-break-before: always;
}
In some cases, i.e. when (if) you're just using float
to have elements flow on the same "line", you might use
display: inline-block;
instead of
float: left;
Otherwise, using a clear
element at the end works, even if it may go against the grain to need an element to do what should be CSS work.
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
In a nutshell :
-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record
-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.
See this article on alistapart.com. (Ed: The article has been updated since originally linked)
self
is being used to maintain a reference to the original this
even as the context is changing. It's a technique often used in event handlers (especially in closures).
Edit: Note that using self
is now discouraged as window.self
exists and has the potential to cause errors if you are not careful.
What you call the variable doesn't particularly matter. var that = this;
is fine, but there's nothing magic about the name.
Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.
For example, a simple event callback:
function MyConstructor(options) {_x000D_
let that = this;_x000D_
_x000D_
this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
document.addEventListener('click', (event) => {_x000D_
alert(that.someprop);_x000D_
});_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
someprop: "Hello World"_x000D_
});
_x000D_
Where is the documentation which lists the format specifiers supported by the
Date()
object?
I stumbled across this today and was quite surprised that no one took the time to answer this simple question. True, there are many libraries out there to help with date manipulation. Some are better than others. But that wasn't the question asked.
AFAIK, pure JavaScript doesn't support format specifiers the way you have indicated you'd like to use them. But it does support methods for formatting dates and/or times, such as .toLocaleDateString()
, .toLocaleTimeString()
, and .toUTCString()
.
The Date
object reference I use most frequently is on the w3schools.com website (but a quick Google search will reveal many more that may better meet your needs).
Also note that the Date Object Properties section provides a link to prototype
, which illustrates some ways you can extend the Date object with custom methods. There has been some debate in the JavaScript community over the years about whether or not this is best practice, and I am not advocating for or against it, just pointing out its existence.
*:noh* *:nohlsearch* :noh[lsearch] Stop the highlighting for the 'hlsearch' option. It is automatically turned back on when using a search command, or setting the 'hlsearch' option. This command doesn't work in an autocommand, because the highlighting state is saved and restored when executing autocommands |autocmd-searchpat|. Same thing for when invoking a user function.
I found it just under :help #
, which I keep hitting all the time, and which highlights all the words on the current page like the current one.
<!--This yearpicker development from Zlatko Borojevic_x000D_
html elemnts can generate with java function_x000D_
and then declare as custom type for easy use in all html documents _x000D_
For this version for implementacion in your document can use:_x000D_
1. Save this code for example: "yearonly.html"_x000D_
2. creaate one div with id="yearonly"_x000D_
3. Include year picker with function: $("#yearonly").load("yearonly.html"); _x000D_
_x000D_
<div id="yearonly"></div>_x000D_
<script>_x000D_
$("#yearonly").load("yearonly.html"); _x000D_
</script>_x000D_
-->_x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<meta name="viewport" content="text-align:center; width=device-width, initial-scale=1.0">_x000D_
<html>_x000D_
<body>_x000D_
<style>_x000D_
.ydiv {_x000D_
border:solid 1px;_x000D_
width:200px;_x000D_
//height:150px;_x000D_
background-color:#D8D8D8;_x000D_
display:none;_x000D_
position:absolute;_x000D_
top:40px;_x000D_
}_x000D_
_x000D_
.ybutton {_x000D_
_x000D_
border: none;_x000D_
width:35px;_x000D_
height:35px;_x000D_
background-color:#D8D8D8;_x000D_
font-size:100%;_x000D_
}_x000D_
_x000D_
.yhr {_x000D_
background-color:black;_x000D_
color:black;_x000D_
height:1px">_x000D_
}_x000D_
_x000D_
.ytext {_x000D_
border:none;_x000D_
text-align:center;_x000D_
width:118px;_x000D_
font-size:100%;_x000D_
background-color:#D8D8D8;_x000D_
font-weight:bold;_x000D_
_x000D_
}_x000D_
</style>_x000D_
<p>_x000D_
<!-- input text for display result of yearpicker -->_x000D_
<input type = "text" id="yeardate"><button style="width:21px;height:21px"onclick="enabledisable()">V</button></p>_x000D_
_x000D_
<!-- yearpicker panel for change only year-->_x000D_
<div class="ydiv" id = "yearpicker">_x000D_
<button class="ybutton" style="font-weight:bold;"onclick="changedecade('back')"><</button>_x000D_
_x000D_
<input class ="ytext" id="dec" type="text" value ="2018" >_x000D_
_x000D_
<button class="ybutton" style="font-weight:bold;" onclick="changedecade('next')">></button>_x000D_
<hr></hr>_x000D_
_x000D_
_x000D_
_x000D_
<!-- subpanel with one year 0-9 -->_x000D_
<button class="ybutton" onclick="yearone = 0;setyear()">0</button>_x000D_
<button class="ybutton" onclick="yearone = 1;setyear()">1</button>_x000D_
<button class="ybutton" onclick="yearone = 2;setyear()">2</button>_x000D_
<button class="ybutton" onclick="yearone = 3;setyear()">3</button>_x000D_
<button class="ybutton" onclick="yearone = 4;setyear()">4</button><br>_x000D_
<button class="ybutton" onclick="yearone = 5;setyear()">5</button>_x000D_
<button class="ybutton" onclick="yearone = 6;setyear()">6</button>_x000D_
<button class="ybutton" onclick="yearone = 7;setyear()">7</button>_x000D_
<button class="ybutton" onclick="yearone = 8;setyear()">8</button>_x000D_
<button class="ybutton" onclick="yearone = 9;setyear()">9</button>_x000D_
</div>_x000D_
<!-- end year panel -->_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
var date = new Date();_x000D_
var year = date.getFullYear(); //get current year_x000D_
//document.getElementById("yeardate").value = year;// can rem if filing text from database_x000D_
_x000D_
var yearone = 0;_x000D_
_x000D_
function changedecade(val1){ //change decade for year_x000D_
_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
if (val1 == "next"){_x000D_
document.getElementById('dec').value = x + 10;_x000D_
}else{_x000D_
document.getElementById('dec').value = x - 10;_x000D_
}_x000D_
}_x000D_
_x000D_
function setyear(){ //set full year as sum decade and one year in decade_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
var y = parseFloat(yearone);_x000D_
_x000D_
var suma = x + y;_x000D_
var d = new Date();_x000D_
d.setFullYear(suma);_x000D_
var year = d.getFullYear();_x000D_
document.getElementById("dec").value = year;_x000D_
document.getElementById("yeardate").value = year;_x000D_
document.getElementById("yearpicker").style.display = "none";_x000D_
yearone = 0;_x000D_
}_x000D_
_x000D_
function enabledisable(){ //enable/disable year panel_x000D_
if (document.getElementById("yearpicker").style.display == "block"){_x000D_
document.getElementById("yearpicker").style.display = "none";}else{_x000D_
document.getElementById("yearpicker").style.display = "block";_x000D_
}_x000D_
_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I think unless you want to do the "boolean thing" the only solution is actually to throw. Which you obviously shouldn't do..!
Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.
The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.
[TestMethod]
public void TestLastModifiedTimeStamps()
{
var tempFile = Path.GetTempFileName();
var lastModified = File.GetLastWriteTime(tempFile);
using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
}
Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
}
See File.GetLastWriteTime seems to be returning 'out of date' value
Your options:
a) live with the occasional omissions.
b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).
c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.
/// <summary>
/// type to set signals or check for them using a central file
/// </summary>
public class FileSignal
{
/// <summary>
/// path to the central file for signal control
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// numbers of retries when not able to retrieve (exclusive) file access
/// </summary>
public int MaxCollisions { get; private set; }
/// <summary>
/// timespan to wait until next try
/// </summary>
public TimeSpan SleepOnCollisionInterval { get; private set; }
/// <summary>
/// Timestamp of the last signal
/// </summary>
public DateTime LastSignal { get; private set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
/// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
/// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
{
FilePath = filePath;
MaxCollisions = maxCollisions;
SleepOnCollisionInterval = sleepOnCollisionInterval;
LastSignal = GetSignalTimeStamp();
}
/// <summary>
/// constructor using a default value of 50 ms for sleepOnCollisionInterval
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
/// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
{
}
/// <summary>
/// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
/// </summary>
/// <param name="filePath">path to the central file for signal control</param>
public FileSignal(string filePath) : this(filePath, 10)
{
}
private Stream GetFileStream(FileAccess fileAccess)
{
var i = 0;
while (true)
{
try
{
return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
}
catch (Exception e)
{
i++;
if (i >= MaxCollisions)
{
throw e;
}
Thread.Sleep(SleepOnCollisionInterval);
};
};
}
private DateTime GetSignalTimeStamp()
{
if (!File.Exists(FilePath))
{
return DateTime.MinValue;
}
using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
if(stream.Length == 0)
{
return DateTime.MinValue;
}
using (var reader = new BinaryReader(stream))
{
return DateTime.FromBinary(reader.ReadInt64());
};
}
}
/// <summary>
/// overwrites the existing central file and writes the current time into it.
/// </summary>
public void Signal()
{
LastSignal = DateTime.Now;
using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(LastSignal.ToBinary());
}
}
}
/// <summary>
/// returns true if the file signal has changed, otherwise false.
/// </summary>
public bool CheckIfSignalled()
{
var signal = GetSignalTimeStamp();
var signalTimestampChanged = LastSignal != signal;
LastSignal = signal;
return signalTimestampChanged;
}
}
Some tests for it:
[TestMethod]
public void TestSignal()
{
var fileSignal = new FileSignal(Path.GetTempFileName());
var fileSignal2 = new FileSignal(fileSignal.FilePath);
Assert.IsFalse(fileSignal.CheckIfSignalled());
Assert.IsFalse(fileSignal2.CheckIfSignalled());
Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
fileSignal.Signal();
Assert.IsFalse(fileSignal.CheckIfSignalled());
Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
Assert.IsTrue(fileSignal2.CheckIfSignalled());
Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
Assert.IsFalse(fileSignal2.CheckIfSignalled());
}
Follow below steps-
Step1 - Ctrl+Shift+P
Step2 - Enter Disable Package
Step3 - enter the package name that you want to disable and press enter
Successfully removed, if not removed then restart Sublime
panel.setStyle("-fx-background-color: #FFFFFF;");
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
There is one more stacktrace feature offered by Throwable family - the possibility to manipulate stack trace information.
Standard behavior:
package test.stack.trace;
public class SomeClass {
public void methodA() {
methodB();
}
public void methodB() {
methodC();
}
public void methodC() {
throw new RuntimeException();
}
public static void main(String[] args) {
new SomeClass().methodA();
}
}
Stack trace:
Exception in thread "main" java.lang.RuntimeException
at test.stack.trace.SomeClass.methodC(SomeClass.java:18)
at test.stack.trace.SomeClass.methodB(SomeClass.java:13)
at test.stack.trace.SomeClass.methodA(SomeClass.java:9)
at test.stack.trace.SomeClass.main(SomeClass.java:27)
Manipulated stack trace:
package test.stack.trace;
public class SomeClass {
...
public void methodC() {
RuntimeException e = new RuntimeException();
e.setStackTrace(new StackTraceElement[]{
new StackTraceElement("OtherClass", "methodX", "String.java", 99),
new StackTraceElement("OtherClass", "methodY", "String.java", 55)
});
throw e;
}
public static void main(String[] args) {
new SomeClass().methodA();
}
}
Stack trace:
Exception in thread "main" java.lang.RuntimeException
at OtherClass.methodX(String.java:99)
at OtherClass.methodY(String.java:55)
In newer versions of Notepad++ (currently 5.9), this option is under:
View->Show Symbol->Show All Characters
or
View->Show Symbol->Show White Space and Tab
Because of an annoying design choice in Ruby before 1.9 — some_string[0]
returns the character code of the first character — the most portable way to write this is some_string[0,1]
, which tells it to get a substring at index 0 that's 1 character long.
I had the problem of date picker mixed with month picker. I solved it like that.
$('.monthpicker').focus(function()
{
$(".ui-datepicker-calendar").show();
}).datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM/yy',
create: function (input, inst) {
},
onClose: function(dateText, inst) {
var month = 1+parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val());
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
}
});
For the record, what killed the process on my Raspberry 3B+ (running raspbian) was Ctrl+'. On my French AZERTY keyboard, the touch ' is also number 4.
cat foo.txt | strings -n 8 > bar.txt
will do the job.
You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:
gcd_alg:
subl %ecx, %eax /* a = a - c */
cmpl $0, %eax /* if a == 0 */
je gcd_done /* jump to end */
cmpl %ecx, %eax /* if a < c */
jl gcd_preswap /* swap and start over */
jmp gcd_alg /* keep subtracting */
Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.
As for clearing the screen, that depends on the system you're using.
This is an old, answered, question, but @Alexandre asked "Why would anyone want to do this?", and I thought that I might provide an example usage that I am considering this afternoon.
Legacy code. Uses naked pointers Obj*obj with a delete obj at the end.
Unfortunately I need sometimes, not often, to keep the object alive longer.
I am considering making it a reference counted smart pointer. But there would be lots of code to change, if I was to use ref_cnt_ptr<Obj>
everywhere. And if you mix naked Obj* and ref_cnt_ptr, you can get the object implicitly deleted when the last ref_cnt_ptr goes away, even though there are Obj* still alive.
So I am thinking about creating an explicit_delete_ref_cnt_ptr. I.e. a reference counted pointer where the delete is only done in an explicit delete routine. Using it in the one place where the existing code knows the lifetime of the object, as well as in my new code that keeps the object alive longer.
Incrementing and decrementing the reference count as explicit_delete_ref_cnt_ptr get manipulated.
But NOT freeing when the reference count is seen to be zero in the explicit_delete_ref_cnt_ptr destructor.
Only freeing when the reference count is seen to be zero in an explicit delete-like operation. E.g. in something like:
template<typename T> class explicit_delete_ref_cnt_ptr {
private:
T* ptr;
int rc;
...
public:
void delete_if_rc0() {
if( this->ptr ) {
this->rc--;
if( this->rc == 0 ) {
delete this->ptr;
}
this->ptr = 0;
}
}
};
OK, something like that. It's a bit unusual to have a reference counted pointer type not automatically delete the object pointed to in the rc'ed ptr destructor. But it seems like this might make mixing naked pointers and rc'ed pointers a bit safer.
But so far no need for delete this.
But then it occurred to me: if the object pointed to, the pointee, knows that it is being reference counted, e.g. if the count is inside the object (or in some other table), then the routine delete_if_rc0 could be a method of the pointee object, not the (smart) pointer.
class Pointee {
private:
int rc;
...
public:
void delete_if_rc0() {
this->rc--;
if( this->rc == 0 ) {
delete this;
}
}
}
};
Actually, it doesn't need to be a member method at all, but could be a free function:
map<void*,int> keepalive_map;
template<typename T>
void delete_if_rc0(T*ptr) {
void* tptr = (void*)ptr;
if( keepalive_map[tptr] == 1 ) {
delete ptr;
}
};
(BTW, I know the code is not quite right - it becomes less readable if I add all the details, so I am leaving it like this.)
Just something to watch out for......
In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below
USE [MyDatabase]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END
GO
USE [MyDatabase]
GO
ALTER TABLE [Patient].[Detail] ADD CONSTRAINT [DEF_Detail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]
GO
Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).
The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.
To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.
(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')
Configuring and running the maven-eclipse plugin, (for example from the command line mvn eclipse:eclipse
)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
JPG > Joint Photographic Experts Group
1 JPG images support 16 million colors and are best suited for photographs and complex graphics
2 JPGs do not support transparency.
PNG > Portable Network Graphics
1 It's used as an alternative to the GIF file format when the GIF technology was copyrighted and required permission to use.
2 PNGs allow for 5 to 25 percent greater compression than GIFs, and with a wider range of colors. PNGs use two-dimensional interlacing, which makes them load twice as fast as GIF images.”
3 Image that has a lot of colors or requires advanced variable transparency, PNG is the preferred file type.
GIF > Graphics Interchange Format
1 Reduces the number of colors in an image to 256.
2 GIFs also support transparency.
3 GIFs have the unique ability to display a sequence of images, similar to videos, called an animated GIF.
4 If the image has few colors and does not require any advanced alpha transparency effect, GIF is the way to go.
SVG > Scalable Vector Graphics
1 SVGs are a web standard based on XML that describe both static images and animations in two dimensions.
2 SVG allows you to create very high-quality graphics and animations that do not lose detail as their size increases/decreases.
you can use either the ADD command https://docs.docker.com/engine/reference/builder/#/add or the COPY command https://docs.docker.com/engine/reference/builder/#/copy
I listed dates of 2 Weeks later. You can use variable @period OR function datediff(dd, @date_start, @date_end)
declare @period INT, @date_start datetime, @date_end datetime, @i int;
set @period = 14
set @date_start = convert(date,DATEADD(D, -@period, curent_timestamp))
set @date_end = convert(date,current_timestamp)
set @i = 1
create table #datesList(dts datetime)
insert into #datesList values (@date_start)
while @i <= @period
Begin
insert into #datesList values (dateadd(d,@i,@date_start))
set @i = @i + 1
end
select cast(dts as DATE) from #datesList
Drop Table #datesList
This command works like a charm for me:
for /r "$(SolutionDir)libraries" %%f in (*.dll, *.exe) do @xcopy "%%f" "$(TargetDir)"
It recursively copies every dll
and exe
file from MySolutionPath\libraries
into the bin\debug
or bin\release
.
You can find more info in here
A good way to achieve this is to have a Maven mirror server such as Sonatype Nexus. It is free and very easy to setup (Java web app). With Nexus one can have private (team, corporate etc) repository with a capability of deploying third party and internal apps into it, while also registering other Maven repositories as part of the same server. This way the local Maven settings would reference only the one private Nexus server and all the dependencies will be resolved using it.
I faced a similar problem. The problem in my case was, Number of rows in X was not equal to number of rows in y.
i.e. number of entries in feature columns was not equal to number of entires in target variable since I had dropped some rows from freature columns.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
class AppProvider extends Component {
constructor() {
super();
window.alertMessage = this.alertMessage.bind(this);
}
alertMessage() {
console.log('Hello World');
}
}
You can call this method from the window by using window.alertMessage()
.
It's hard to tell what you're going for in that example. exports =
is about exporting from external modules, but the code sample you linked is an internal module.
Rule of thumb: If you write module foo { ... }
, you're writing an internal module; if you write export something something
at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo
at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo
in a file that had a top-level export (since foo
would not be externally visible).
The following things make sense (each scenario delineated by a horizontal rule):
// An internal module named SayHi with an exported function 'foo'
module SayHi {
export function foo() {
console.log("Hi");
}
export class bar { }
}
// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();
file1.ts
// This *file* is an external module because it has a top-level 'export'
export function foo() {
console.log('hi');
}
export class bar { }
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();
file1.ts
// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g
Other answers indicate perfectly well that --no-ff
results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.
This answer may provide context for when to use or not to use --no-ff
.
--no-ff
Worked example:
$ git checkout -b NewFeature
[work...work...work]
$ git commit -am "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature
--no-ff
Worked example:
$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]
You can use the below method:
# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
if file not in ephFiles:
noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.
Thank you.
if not %1 == "" (
must be
if not "%1" == "" (
If an argument isn't given, it's completely empty, not even ""
(which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.
No, there are definitely times where you would not want to use [unowned self]
. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called.
If you are making an asynchronous network request you do want the closure to retain self
for when the request finishes. That object may have otherwise been deallocated but you still want to be able to handle the request finishing.
unowned self
or weak self
The only time where you really want to use [unowned self]
or [weak self]
is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.
In the specific case of a closure, you just need to realize that any variable that is referenced inside of it, gets "owned" by the closure. As long as the closure is around, those objects are guaranteed to be around. The only way to stop that ownership, is to do the [unowned self]
or [weak self]
. So if a class owns a closure, and that closure captures a strong reference to that class, then you have a strong reference cycle between the closure and the class. This also includes if the class owns something that owns the closure.
In the example on the slide, TempNotifier
owns the closure through the onChange
member variable. If they did not declare self
as unowned
, the closure would also own self
creating a strong reference cycle.
unowned
and weak
The difference between unowned
and weak
is that weak
is declared as an Optional while unowned
is not. By declaring it weak
you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned
variable that happens to be nil, it will crash the whole program. So only use unowned
when you are positive that variable will always be around while the closure is around
AFNetworking for Android:
Fast Android Networking is here
Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
Fast Android Networking Library supports downloading any type of file
Fast Android Networking Library supports uploading any type of file (supports multipart upload)
Fast Android Networking Library supports cancelling a request
Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
Fast Android Networking Library supports RxJava
As it uses OkHttp as a networking layer, it supports:
Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
Transparent GZIP shrinks download sizes
Fast Android Networking Library supports response caching which avoids the network completely for repeat requests
Thanks: The library is created by me
They use regular CSS.
Just use your regular font family like this:
font-family: 'Open Sans', sans-serif;
Now you decide what "weight" the font should have by adding
for semi-bold
font-weight:600;
for bold (700)
font-weight:bold;
for extra bold (800)
font-weight:800;
Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.
Pretty smart :-)
Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.
For example the following link will include both weights 400 and 700:
<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");
The first parameter is the path. The second is the search pattern you want to use.
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
Just add !
before an exclusion rule.
According to the gitignore man page:
Patterns have the following format:
...
- An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
The problem is that the directory you created, /data/db
is owned by and only writable by the root user, but you are running mongod as yourself. There are several ways to resolve this, but ultimately, you must give the directory in question the right permissions. If this is for production, I would advise you to check the docs and think this over carefully -- you probably want to take special care.
However, if this is just for testing and you just need this to work and get on with it, you could try this, which will make the directory writable by everyone:
> sudo chmod -R go+w /data/db
or this, which will make the directory owned by you:
> sudo chown -R $USER /data/db
Find this tuple:
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You need to add to 'DIRS' the string
"os.path.join(SETTINGS_PATH, 'templates')"
So altogether you need:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
yes It is possible.. returns type can be different only if parent class method return type is
a super type of child class method return type..
means
class ParentClass {
public Circle() method1() {
return new Cirlce();
}
}
class ChildClass extends ParentClass {
public Square method1() {
return new Square();
}
}
Class Circle {
}
class Square extends Circle {
}
Here is my solution please check and modify according your requirements
function getHowLongAgo($date, $display = array('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second'), $ago = '') {
date_default_timezone_set('Australia/Sydney');
$timestamp = strtotime($date);
$timestamp = (int) $timestamp;
$current_time = time();
$diff = $current_time - $timestamp;
//intervals in seconds
$intervals = array(
'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60
);
//now we just find the difference
if ($diff == 0) {
return ' Just now ';
}
if ($diff < 60) {
return $diff == 1 ? $diff . ' second ago ' : $diff . ' seconds ago ';
}
if ($diff >= 60 && $diff < $intervals['hour']) {
$diff = floor($diff / $intervals['minute']);
return $diff == 1 ? $diff . ' minute ago ' : $diff . ' minutes ago ';
}
if ($diff >= $intervals['hour'] && $diff < $intervals['day']) {
$diff = floor($diff / $intervals['hour']);
return $diff == 1 ? $diff . ' hour ago ' : $diff . ' hours ago ';
}
if ($diff >= $intervals['day'] && $diff < $intervals['week']) {
$diff = floor($diff / $intervals['day']);
return $diff == 1 ? $diff . ' day ago ' : $diff . ' days ago ';
}
if ($diff >= $intervals['week'] && $diff < $intervals['month']) {
$diff = floor($diff / $intervals['week']);
return $diff == 1 ? $diff . ' week ago ' : $diff . ' weeks ago ';
}
if ($diff >= $intervals['month'] && $diff < $intervals['year']) {
$diff = floor($diff / $intervals['month']);
return $diff == 1 ? $diff . ' month ago ' : $diff . ' months ago ';
}
if ($diff >= $intervals['year']) {
$diff = floor($diff / $intervals['year']);
return $diff == 1 ? $diff . ' year ago ' : $diff . ' years ago ';
}
}
Thanks
I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)
vw and vh stand for viewport width and viewport height respectively.
The difference between using width: 100vw
instead of width: 100%
is that while 100%
will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.
If you set the style body { margin: 0 }
, 100vw should behave the same as 100%.
Using vw
as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.
You can set font-size: 1vw
(or whatever size suits your project) in your body
CSS and everything specified in rem
units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.
Emulation may seem daunting but is actually quite easier than simulating.
Any processor typically has a well-written specification that describes states, interactions, etc.
If you did not care about performance at all, then you could easily emulate most older processors using very elegant object oriented programs. For example, an X86 processor would need something to maintain the state of registers (easy), something to maintain the state of memory (easy), and something that would take each incoming command and apply it to the current state of the machine. If you really wanted accuracy, you would also emulate memory translations, caching, etc., but that is doable.
In fact, many microchip and CPU manufacturers test programs against an emulator of the chip and then against the chip itself, which helps them find out if there are issues in the specifications of the chip, or in the actual implementation of the chip in hardware. For example, it is possible to write a chip specification that would result in deadlocks, and when a deadline occurs in the hardware it's important to see if it could be reproduced in the specification since that indicates a greater problem than something in the chip implementation.
Of course, emulators for video games usually care about performance so they don't use naive implementations, and they also include code that interfaces with the host system's OS, for example to use drawing and sound.
Considering the very slow performance of old video games (NES/SNES, etc.), emulation is quite easy on modern systems. In fact, it's even more amazing that you could just download a set of every SNES game ever or any Atari 2600 game ever, considering that when these systems were popular having free access to every cartridge would have been a dream come true.
It may be related to the difference between:
If each line does end in an end-of-line, this avoids, for instance, that concatenating two text files would make the last line of the first run into the first line of the second.
Plus, an editor can check at load whether the file ends in an end-of-line, saves it in its local option 'eol', and uses that when writing the file.
A few years back (2005), many editors (ZDE, Eclipse, Scite, ...) did "forget" that final EOL, which was not very appreciated.
Not only that, but they interpreted that final EOL incorrectly, as 'start a new line', and actually start to display another line as if it already existed.
This was very visible with a 'proper' text file with a well-behaved text editor like vim, compared to opening it in one of the above editors. It displayed an extra line below the real last line of the file. You see something like this:
1 first line
2 middle line
3 last line
4
$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.
When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.
<div ng-view></div>
$routeProvider
.when('/contact/', {
templateUrl: 'app/views/core/contact/contact.html',
controller: 'ContactCtrl'
});
<div ui-view>
<div ui-view='abc'></div>
<div ui-view='abc'></div>
</div>
$stateProvider
.state("contact", {
url: "/contact/",
templateUrl: '/app/Aisel/Contact/views/contact.html',
controller: 'ContactCtrl'
});
SELECT array_to_string(array(SELECT a FROM b),', ');
Will do as well.
We got the error:
GET http://localhost/pathToWebSite/somePage.aspx raised an http.status: 0 error
That call is made from windows task that calls a VBS file, so to troubleshoot the problem, pointed a browser to the url and we get a Privacy Error:
Your connection is not private
Attackers might be trying to steal your information from localhost (for example, passwords, messages, or credit cards). NET::ERR_CERT_COMMON_NAME_INVALID
Automatically report details of possible security incidents to Google. Privacy policy Back to safety This server could not prove that it is localhost; its security certificate is from *.ourdomain.com. This may be caused by a misconfiguration or an attacker intercepting your connection. Learn more.
This is because we have a IIS URL Rewrite rule set to force connections use https. That rule diverts http://localhost to https://localhost but our SSL certificate is based on an outside facing domain name not localhost, thus the error which is reported as status code 0. So a Privacy error could be a very obscure reason for this status code 0.
In our case the solution was to add an exception to the rule for localhost and allow http://localhost/pathToWebSite/somePage.aspx to use http. Obscure, yes, but I'll run into this next year and now I'll find my answer in a google search.
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
The difference is that if you only specify the DOCTYPE
, IE’s Compatibility View Settings take precedence. By default these settings force all intranet sites into Compatibility View regardless of DOCTYPE
. There’s also a checkbox to use Compatibility View for all websites, regardless of DOCTYPE
.
X-UA-Compatible
overrides the Compatibility View Settings, so the page will render in standards mode regardless of the browser settings. This forces standards mode for:
DOCTYPE
alone cannot do that; you will end up in one of the Compatibility View modes in these cases regardless of DOCTYPE
.
If both the meta
tag and the HTTP header are specified, the meta
tag takes precedence.
This answer is based on examining the complete rules for deciding document mode in IE8, IE9, and IE10. Note that looking at the DOCTYPE
is the very last fallback for deciding the document mode.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
Here's another idea. You have to remember, that it's .NET underneath:
$arr = [System.Array]::CreateInstance([System.Object], 5)
$arr.GetType()
$arr.Length
$arr = [Object[]]::new(5)
$arr.GetType()
$arr.Length
Result:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
5
True True Object[] System.Array
5
Using new()
has one distinct advantage: when you're programming in ISE and want to create an object, ISE will give you hint with all paramer combinations and their types. You don't have that with New-Object
, where you have to remember the types and order of arguments.
The question was: "Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?"
Ten years ago the answer was probably 'No'. However, times have changed. In 2020 it is finally possible to create a fully accessible, native, non-jquery HTML5 slider with two thumbs for price ranges. If found this posted after I already created this solution and I thought that it would be nice to share my implementation here.
This implementation has been tested on mobile Chrome and Firefox (Android) and Chrome and Firefox (Linux). I am not sure about other platforms, but it should be quite good. I would love to get your feedback and improve this solution.
This solution allows multiple instances on one page and it consists of just two inputs (each) with descriptive labels for screen readers. You can set the thumb size in the amount of grid labels. Also, you can use touch, keyboard and mouse to interact with the slider. The value is updated during adjustment, due to the 'on input' event listener.
My first approach was to overlay the sliders and clip them. However, that resulted in complex code with a lot of browser dependencies. Then I recreated the solution with two sliders that were 'inline'. This is the solution you will find below.
var thumbsize = 14;
function draw(slider,splitvalue) {
/* set function vars */
var min = slider.querySelector('.min');
var max = slider.querySelector('.max');
var lower = slider.querySelector('.lower');
var upper = slider.querySelector('.upper');
var legend = slider.querySelector('.legend');
var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
var rangemin = parseInt(slider.getAttribute('data-rangemin'));
var rangemax = parseInt(slider.getAttribute('data-rangemax'));
/* set min and max attributes */
min.setAttribute('max',splitvalue);
max.setAttribute('min',splitvalue);
/* set css */
min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
min.style.left = '0px';
max.style.left = parseInt(min.style.width)+'px';
min.style.top = lower.offsetHeight+'px';
max.style.top = lower.offsetHeight+'px';
legend.style.marginTop = min.offsetHeight+'px';
slider.style.height = (lower.offsetHeight + min.offsetHeight + legend.offsetHeight)+'px';
/* correct for 1 off at the end */
if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);
/* write value and labels */
max.value = max.getAttribute('data-value');
min.value = min.getAttribute('data-value');
lower.innerHTML = min.getAttribute('data-value');
upper.innerHTML = max.getAttribute('data-value');
}
function init(slider) {
/* set function vars */
var min = slider.querySelector('.min');
var max = slider.querySelector('.max');
var rangemin = parseInt(min.getAttribute('min'));
var rangemax = parseInt(max.getAttribute('max'));
var avgvalue = (rangemin + rangemax)/2;
var legendnum = slider.getAttribute('data-legendnum');
/* set data-values */
min.setAttribute('data-value',rangemin);
max.setAttribute('data-value',rangemax);
/* set data vars */
slider.setAttribute('data-rangemin',rangemin);
slider.setAttribute('data-rangemax',rangemax);
slider.setAttribute('data-thumbsize',thumbsize);
slider.setAttribute('data-rangewidth',slider.offsetWidth);
/* write labels */
var lower = document.createElement('span');
var upper = document.createElement('span');
lower.classList.add('lower','value');
upper.classList.add('upper','value');
lower.appendChild(document.createTextNode(rangemin));
upper.appendChild(document.createTextNode(rangemax));
slider.insertBefore(lower,min.previousElementSibling);
slider.insertBefore(upper,min.previousElementSibling);
/* write legend */
var legend = document.createElement('div');
legend.classList.add('legend');
var legendvalues = [];
for (var i = 0; i < legendnum; i++) {
legendvalues[i] = document.createElement('div');
var val = Math.round(rangemin+(i/(legendnum-1))*(rangemax - rangemin));
legendvalues[i].appendChild(document.createTextNode(val));
legend.appendChild(legendvalues[i]);
}
slider.appendChild(legend);
/* draw */
draw(slider,avgvalue);
/* events */
min.addEventListener("input", function() {update(min);});
max.addEventListener("input", function() {update(max);});
}
function update(el){
/* set function vars */
var slider = el.parentElement;
var min = slider.querySelector('#min');
var max = slider.querySelector('#max');
var minvalue = Math.floor(min.value);
var maxvalue = Math.floor(max.value);
/* set inactive values before draw */
min.setAttribute('data-value',minvalue);
max.setAttribute('data-value',maxvalue);
var avgvalue = (minvalue + maxvalue)/2;
/* draw */
draw(slider,avgvalue);
}
var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
init(slider);
});
_x000D_
* {padding: 0; margin: 0;}
body {padding: 40px;}
.min-max-slider {position: relative; width: 200px; text-align: center; margin-bottom: 50px;}
.min-max-slider > label {display: none;}
span.value {height: 1.7em; font-weight: bold; display: inline-block;}
span.value.lower::before {content: "€"; display: inline-block;}
span.value.upper::before {content: "- €"; display: inline-block; margin-left: 0.4em;}
.min-max-slider > .legend {display: flex; justify-content: space-between;}
.min-max-slider > .legend > * {font-size: small; opacity: 0.25;}
.min-max-slider > input {cursor: pointer; position: absolute;}
/* webkit specific styling */
.min-max-slider > input {
-webkit-appearance: none;
outline: none!important;
background: transparent;
background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}
.min-max-slider > input::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
width: 14px; /* Set a specific slider handle width */
height: 14px; /* Slider handle height */
background: #eee; /* Green background */
cursor: pointer; /* Cursor on hover */
border: 1px solid gray;
border-radius: 100%;
}
.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
_x000D_
<div class="min-max-slider" data-legendnum="2">
<label for="min">Minimum price</label>
<input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
<label for="max">Maximum price</label>
<input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>
_x000D_
Note that you should keep the step size to 1 to prevent the values to change due to redraws/redraw bugs.
View online at: https://codepen.io/joosts/pen/rNLdxvK
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
gzip -dc archive.tar.gz | tar -xf - -C /destination
or, with GNU tar
tar xzf archive.tar.gz -C /destination
The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.
This is another solution to convert HTML to Text or RTF in C#:
SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
h.OutputFormat = HtmlToRtf.eOutputFormat.TextUnicode;
string text = h.ConvertString(htmlString);
This library is not free, this is commercial product and it is my own product.
val() should handle both cases
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
First change the directory to which you want to know the number of lines.
For example, if I want to know the number of lines in all files of a directory named sample, give $cd sample
.
Then try the command $wc -l *
. This will return the number of lines for each file and also the total number of lines in the entire directory at the end.
I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse. And there is no leak problem here.
private var kAssociationKeyMaxLength: Int = 0
extension UITextField {
@IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length
} else {
return Int.max
}
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
//The method is used to cancel the check when use Chinese Pinyin input method.
//Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
func isInputMethod() -> Bool {
if let positionRange = self.markedTextRange {
if let _ = self.position(from: positionRange.start, offset: 0) {
return true
}
}
return false
}
func checkMaxLength(textField: UITextField) {
guard !self.isInputMethod(), let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
text = prospectiveText.substring(to: maxCharIndex)
selectedTextRange = selection
}
}
There is a super simple way.
in BaseActivity, Activity or Fragment override attachBaseContext
override fun attachBaseContext(context: Context) {
super.attachBaseContext(context.changeLocale("tr"))
}
extension
fun Context.changeLocale(language:String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val config = this.resources.configuration
config.setLocale(locale)
return createConfigurationContext(config)
}
The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).
You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.
note - Lepl is no longer maintained or supported.
RFC 3696 defines "best practices" for URL validation - http://www.faqs.org/rfcs/rfc3696.html
The latest release of Lepl (a Python parser library) includes an implementation of RFC 3696. You would use it something like:
from lepl.apps.rfc3696 import Email, HttpUrl
# compile the validators (do once at start of program)
valid_email = Email()
valid_http_url = HttpUrl()
# use the validators (as often as you like)
if valid_email(some_email):
# email is ok
else:
# email is bad
if valid_http_url(some_url):
# url is ok
else:
# url is bad
Although the validators are defined in Lepl, which is a recursive descent parser, they are largely compiled internally to regular expressions. That combines the best of both worlds - a (relatively) easy to read definition that can be checked against RFC 3696 and an efficient implementation. There's a post on my blog showing how this simplifies the parser - http://www.acooke.org/cute/LEPLOptimi0.html
Lepl is available at http://www.acooke.org/lepl and the RFC 3696 module is documented at http://www.acooke.org/lepl/rfc3696.html
This is completely new in this release, so may contain bugs. Please contact me if you have any problems and I will fix them ASAP. Thanks.
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
if you want to update your react and react-dom version in your existing react step then run this command I hope You get the latest version of react and react-dom.
Thanks
npm install react@latest react-dom@latest
Most answers point to except (…) as (…):
syntax (rightly so) but at the same time nobody wants to talk about an elephant in the room, where the elephant is sys.exc_info()
function.
From the documentation of sys module (emphasis mine):
This function returns a tuple of three values that give information about the exception that is currently being handled.
(…)
If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.
I think the sys.exc_info()
could be treated as the most direct answer to the original question of How do I know what type of exception occurred?
As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.
def sequences_contain_same_items(a, b):
for item in a:
try:
i = b.index(item)
except ValueError:
return False
b = b[:i] + b[i+1:]
return not b
Updated answer for MVC 4, heavily borrowed from this page and ASP.NET MVC issue with configuration of forms authentication section (and answered on both pages)
<appSettings>
...
<add key="PreserveLoginUrl" value="true" />
</appSettings>
...
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="43200" /> <!--43,200 in minutes - 30 days-->
</authentication>
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
Below is the perfect one for mentioned requirement :
^[0-9]{1,3}(,[0-9]{3})*(([\\.,]{1}[0-9]*)|())$
I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: blue;_x000D_
transform: translateY(-100%);_x000D_
-webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
animation: slide-in 0.5s forwards;_x000D_
-webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
animation: slide-out 0.5s forwards;_x000D_
-webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
_x000D_
@keyframes slide-in {_x000D_
100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@keyframes slide-out {_x000D_
0% { transform: translateY(0%); }_x000D_
100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
0% { -webkit-transform: translateY(0%); }_x000D_
100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
If you want to center align an element without knowing it's width and height do:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Example:
*{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}_x000D_
section{_x000D_
background:red;_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
}_x000D_
div{ _x000D_
width: 80vw;_x000D_
height: 80vh;_x000D_
background: white;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<section>_x000D_
<div>_x000D_
<h1>Popup</h1>_x000D_
</div>_x000D_
</section>
_x000D_
Insert can only operate on one table at a time. Multiple Inserts have to have multiple statements.
I don't know that you need to do the looping through a table variable - can't you just use a mass insert into one table, then the mass insert into the other?
By the way - I am guessing you mean copy the data from Object_Table; otherwise the question does not make sense.
I could achieve a button using jQueryMobile with following code:
<label for="ppt" data-role="button" data-inline="true" data-mini="true" data-corners="false">Upload</label>
<input id="ppt" type="file" name="ppt" multiple data-role="button" data-inline="true" data-mini="true" data-corners="false" style="opacity: 0;"/>
Above code creates a "Upload" button (custom text). On click of upload button, file browse is launched. Tested with Chrome 25 & IE9.
This tool gave me following results which helps me achieve the task as following code.
<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
function play(){
document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
}
</script>
Example for wait() and notifyall() in Threading.
A synchronized static array list is used as resource and wait() method is called if the array list is empty. notify() method is invoked once a element is added for the array list.
public class PrinterResource extends Thread{
//resource
public static List<String> arrayList = new ArrayList<String>();
public void addElement(String a){
//System.out.println("Add element method "+this.getName());
synchronized (arrayList) {
arrayList.add(a);
arrayList.notifyAll();
}
}
public void removeElement(){
//System.out.println("Remove element method "+this.getName());
synchronized (arrayList) {
if(arrayList.size() == 0){
try {
arrayList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
arrayList.remove(0);
}
}
}
public void run(){
System.out.println("Thread name -- "+this.getName());
if(!this.getName().equalsIgnoreCase("p4")){
this.removeElement();
}
this.addElement("threads");
}
public static void main(String[] args) {
PrinterResource p1 = new PrinterResource();
p1.setName("p1");
p1.start();
PrinterResource p2 = new PrinterResource();
p2.setName("p2");
p2.start();
PrinterResource p3 = new PrinterResource();
p3.setName("p3");
p3.start();
PrinterResource p4 = new PrinterResource();
p4.setName("p4");
p4.start();
try{
p1.join();
p2.join();
p3.join();
p4.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Final size of arraylist "+arrayList.size());
}
}
I solved it this way.
Using jquery
$('#tab').append($('<tr>')
.append($('<td>').append("text1"))
.append($('<td>').append("text2"))
.append($('<td>').append("text3"))
.append($('<td>').append("text4"))
)
$('#tab').append($('<tr>')_x000D_
.append($('<td>').append("text1"))_x000D_
.append($('<td>').append("text2"))_x000D_
.append($('<td>').append("text3"))_x000D_
.append($('<td>').append("text4"))_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table id="tab">_x000D_
<tr>_x000D_
<th>Firstname</th>_x000D_
<th>Lastname</th> _x000D_
<th>Age</th>_x000D_
<th>City</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jill</td>_x000D_
<td>Smith</td> _x000D_
<td>50</td>_x000D_
<td>New York</td>_x000D_
</tr>_x000D_
</table>
_x000D_
To assign, you should use p=p+1;
instead of p+1=p;
int main()
{
int x[3]={4,5,6};
int *p=x;
p=p+1; /*You just needed to switch the terms around*/
cout<<p<<endl;
getch();
}
I was trying to add List to existing key in dictionary and reached the following solution:
Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);
It will not show any exception and won't replace previous values.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true)
, just write if(condition)
(This way, for example, you'll not write =
by mistake).
I believe you are now able to use Window.getComputedStyle()
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
OS : Win10, Visual Studio 2015
Solution : Go to control panel ---> uninstall program ---MSvisual studio ----> change ---->organize = repair
and repair it. Note that you must connect to internet until repairing finish.
Good luck.
Always encode from unicode to bytes.
In this direction, you get to choose the encoding.
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??
The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.
>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??
This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:
decode
on it.encode
on it.Now, on seeing .encode
on a byte string, Python 2 first tries to implicitly convert it to text (a unicode
object). Similarly, on seeing .decode
on a unicode string, Python 2 implicitly tries to convert it to bytes (a str
object).
These implicit conversions are why you can get Unicode
Decode
Error
when you've called encode
. It's because encoding usually accepts a parameter of type unicode
; when receiving a str
parameter, there's an implicit decoding into an object of type unicode
before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder†, giving you the decoding error inside an encoder.
In fact, in Python 3 the methods str.decode
and bytes.encode
don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.
† ...or whatever coding sys.getdefaultencoding()
mentions; usually this is 'ascii'
You need to initialize whatever members you have in your struct, e.g.:
struct MyStruct {
private:
int someInt_;
float someFloat_;
public:
MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values
};
This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:
variable_name: type_name
or this:
variable_name # type: shinyType
So in your case(if you have a CustomObject
class defined), you can do:
customObj: CustomObject