I'm working on firefox. and I was having the same issue, input type text are auto defined something looks like boxshadow inset, but it's not.
the you want to change is border... just setting border:0;
and you're done.
reverse()
| Django documentation
Let's suppose that in your urls.py
you have defined this:
url(r'^foo$', some_view, name='url_name'),
In a template you can then refer to this url as:
<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>
<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>
This will be rendered as:
<a href="/foo/">link which calls some_view</a>
Now say you want to do something similar in your views.py
- e.g. you are handling some other url (not /foo/
) in some other view (not some_view
) and you want to redirect the user to /foo/
(often the case on successful form submission).
You could just do:
return HttpResponseRedirect('/foo/')
But what if you want to change the url in future? You'd have to update your urls.py
and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.
Instead, you can say:
from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))
This looks through all urls defined in your project for the url defined with the name url_name
and returns the actual url /foo/
.
This means that you refer to the url only by its name
attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py
.
Try to use r.hasNext() instead of r.hasNextLine():
while(r.hasNext()) {
scan = r.next();
Another way to do something similar is with flexbox on a wrapper element, i.e.,
.row {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div class="row">_x000D_
<div>Left</div>_x000D_
<div>Right</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
Did you dispatch the event correctly?
function simulateKeyEvent(character) {
var evt = document.createEvent("KeyboardEvent");
(evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
0, 0, 0, 0,
0, character.charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
If you use jQuery, you could do:
function simulateKeyPress(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}
With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.
Try doing this on the directive scope.$apply(function() { $location.path("/route"); });
Chrome returns C:\fakepath\...
for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()
...
var file = path.split('\\').pop();
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
...or lastIndexOf()
...
var file = path.substr(path.lastIndexOf('\\') + 1);
=VLOOKUP(A2,IF(B1:B3="B",A1:C3,""),1,FALSE)
Ctrl+Shift+Enter
to enter.
I can share how I solved the problem in my case.
It seems that somehow I had mySQL Server 5.7 installed. It didn't show on Add/Remove Programs list in Windows tough so I wasn't aware of it. I marked that after I looked up the XAMPP log.
Just after XAMPP launched it has shown in the log that there is a conflict in mySQL and indicated the folder where my mySQL Server 5.7 is installed. I removed mySQL 5.7 manually from Program Files (x86) and ProgramData folder, restarted and XAMPP mySQL started normally then.
I've tried only stopping the mySQL service but for me it didn't work. Only manually deleting all mySQL 5.7 folders seemed to have helped.
Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.
It will usually be mounted to /mnt but if not run
sudo mount /dev/xvda2 /mnt
To then create a swap file on this device do the following for a 4GB swapfile
sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096
Make sure no other user can view the swap file
sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile
Make and Flag as swap
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
Add/Make sure the following are in your /etc/fstab
/dev/xvda2 /mnt auto defaults,nobootwait,comment=cloudconfig 0 2
/mnt/swapfile swap swap defaults 0 0
lastly enable swap
sudo swapon -a
Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.
So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).
However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.
I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059
All cookies expire as per the cookie specification, so this is not a PHP limitation.
Use a far future date. For example, set a cookie that expires in ten years:
setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.
You can also use
HttpRuntime.AppDomainAppVirtualPath
Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.
You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.
In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).
In HTML5 there is the global hidden
attribute:
When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the
hidden
attribute specified.
Example (using the small
element here, because it’s an "attribution"):
<small hidden>Thanks to John Doe for this idea.</small>
As a fallback (for user-agents that don’t know the hidden
attribute), you can specify in your CSS:
[hidden] {display:none;}
An general element for plain text could be the script
element used as "data block":
<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>
Alternatively, you could also use data-*
attributes on existing elements (resp. on new div
elements if you want to group some elements for the attribution):
<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>
Try this:
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set
[mydict[k] for k in mykeys]
=> [3, 1]
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
Steps to connect Blue Stack with Android Studio
%LocalAppData%\Android\sdk\platform-tools
)adb connect localhost:5555
from this location.When working with a version control system where all files are read only until checked out (like Perforce), the problem may be that you accidentally submitted into this version control system one of the VS files (like filters, for example) and the file thus cannot be overridden during build.
Just go to your working directory and check that none of VS solution related files and none of temporary created files (like all moc_ and ui_ prefixed files in QT, for example) is read only.
If using .NET Core or .NET Standard
use:
Manage NuGet Packages..
instead of:
Add Reference...
Since git version 1.6.3 there is "git difftool" which you can configure to use your favorite graphical diff tool. Currently supported out-of-the-box are kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse and opendiff; if the tool you want to use isn't on this list, you can always use 'difftool.<tool>.cmd
' configuration option.
"git difftool" accepts the same options as "git diff".
Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.
As example you could create your own bundle:
bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
And render it like this:
@Scripts.Render("~/bundles/mybundle")
One more advantage of @Scripts.Render("~/bundles/mybundle")
over the native <script src="~/bundles/mybundle" />
is that @Scripts.Render()
will respect the web.config
debug setting:
<system.web>
<compilation debug="true|false" />
If debug="true"
then it will instead render individual script tags for each source script, without any minification.
For stylesheets you will have to use a StyleBundle and @Styles.Render().
Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.
You could use On Error Resume Next
then there is no need to loop through all the sheets in the workbook.
With On Error Resume Next
the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.
Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.
Dim book
Dim sht as Worksheet
set book= Workbooks("SomeBook.xlsx")
On Error Resume Next
Application.DisplayAlerts=False
Set sht = book.Worksheets("ID Sheet")
sht.Delete
Set sht = book.Worksheets("Summary")
sht.Delete
Application.DisplayAlerts=True
On Error GoTo 0
function yourFunction($var1, $var2, $optional = Null){
... code
}
You can make a regular function and then add your optional variables by giving them a default Null value.
A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
You can use Rout redirecting.
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.RedirectToRoute("CMS_1");
}
which requires to define your routing logic in Global.asax file that could be like that:
routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");
where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
Here's C/C++ recursive function that makes use of dirname()
to traverse bottom-up the directory tree. It will stop as soon as it finds an existing ancestor.
#include <libgen.h>
#include <string.h>
int create_dir_tree_recursive(const char *path, const mode_t mode)
{
if (strcmp(path, "/") == 0) // No need of checking if we are at root.
return 0;
// Check whether this dir exists or not.
struct stat st;
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode))
{
// Check and create parent dir tree first.
char *path2 = strdup(path);
char *parent_dir_path = dirname(path2);
if (create_dir_tree_recursive(parent_dir_path, mode) == -1)
return -1;
// Create this dir.
if (mkdir(path, mode) == -1)
return -1;
}
return 0;
}
naturalWidth and naturalHeight
var img = document.createElement("img");
img.onload = function (event)
{
console.log("natural:", img.naturalWidth, img.naturalHeight);
console.log("width,height:", img.width, img.height);
console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);
// css for tests
img { width:50%;height:50%; }
I have faced the similar issue earlier with Eclipse and STS IDE'S
JDK/JRE
is available or not in your machine. If not please install JDK and setup the environment variables.eclipse.ini
or sts.ini in the following way.-vm C:Program Files (x86)\Java\jre8\bin
All you need to do is change the string within the java.text.SimpleDateFormat
constructor to:
"MM-dd-yyyy HH:mm:ss".
Just use the appropriate letters to build the above string to match your input date.
I prefer using a queue over recursion for this kind of simple traversion:
List<File> allFiles = new ArrayList<File>();
Queue<File> dirs = new LinkedList<File>();
dirs.add(new File("/start/dir/"));
while (!dirs.isEmpty()) {
for (File f : dirs.poll().listFiles()) {
if (f.isDirectory()) {
dirs.add(f);
} else if (f.isFile()) {
allFiles.add(f);
}
}
}
My solution will be to keep text part of tool bar separate, to define style and say, center or whichever alignment. It can be done in XML itself. Some paddings can be specified after doing calculations when you have actions that are visible always. I have moved two attributes from toolbar to its child TextView. This textView can be provided id to be accessed from fragments.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<!--android:theme="@style/defaultTitleTheme"
app:titleTextColor="@color/white"-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingStart="@dimen/icon_size"
android:text="@string/title_home"
style="@style/defaultTitleTheme"
tools:ignore="RtlSymmetry" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
you can use Glide for load and transform into blur image, 1) for only one view,
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view)
2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.
if(isBlure){
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50))
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view )
}else{
val requestOptions = RequestOptions()
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}
You can use an Extention:
public static void CopyOnlyEqualProperties<T>(this T objDest, object objSource) where T : class
{
foreach (PropertyInfo propInfo in typeof(T).GetProperties())
if (objSource.GetType().GetProperties().Any(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()))
propInfo.SetValue(objDest, objSource.GetType().GetProperties().First(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()).GetValue(objSource));
}
In Code:
public class BaseClass
{
public string test{ get; set;}
}
public Derived : BaseClass
{
//Some properies
}
public void CopyProps()
{
BaseClass baseCl =new BaseClass();
baseCl.test="Hello";
Derived drv=new Derived();
drv.CopyOnlyEqualProperties(baseCl);
//Should return Hello to the console now in derived class.
Console.WriteLine(drv.test);
}
The most versatile and most cross-browser solution is to avoid use of the "base" tag, and instead use the target attribute of the "a" tags:
<a target="_parent" href="http://www.stackoverflow.com">Stack Overflow</a>
The <base>
tag is less versatile and browsers are inconsistent in their requirements for its placement within the document, requiring more cross-browser testing. Depending on your project and situation, it can be difficult or even totally unfeasible to achieve the ideal cross-browser placement of the <base>
tag.
Doing this with the target="_parent"
attribute of the <a>
tag is not only more browser-friendly, but also allows you to distinguish between those links you want to open in the iframe, and those you want to open in the parent.
You can turn a stash into a branch if you feel it's important enough:
git stash branch <branchname> [<stash>]
from the man page:
This creates and checks out a new branch named <branchname>
starting from the commit at which the <stash>
was originally created, applies the changes recorded in <stash>
to the new working tree and index, then drops the <stash>
if that completes successfully. When no <stash>
is given, applies the latest one.
This is useful if the branch on which you ran git stash save
has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
You can later rebase this new branch to some other place that's a descendent of where you were when you stashed.
Many possibilities...
You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)
It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)
These files contain user preference configurations that are in general specific to your machine, so it's better not to put it in SCM. Also, VS will change it almost every time you execute it, so it will always be marked by the SCM as 'changed'. I don't include either, I'm in a project using VS for 2 years and had no problems doing that. The only minor annoyance is that the debug parameters (execution path, deployment target, etc.) are stored in one of those files (don't know which), so if you have a standard for them you won't be able to 'publish' it via SCM for other developers to have the entire development environment 'ready to use'.
DESCRIBE all_tab_columns
will show a TABLE_NAME VARCHAR2(30)
Note VARCHAR2(30) means a 30 byte limitation, not a 30 character limitation, and therefore may be different if your database is configured/setup to use a multibyte character set.
Mike
There are three simple ways:
By separator:
s.split("separator") | s.split('/') | s.split(char::is_numeric)
By whitespace:
s.split_whitespace()
By newlines:
s.lines()
By regex: (using regex
crate)
Regex::new(r"\s").unwrap().split("one two three")
The result of each kind is an iterator:
let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());
Under TortoiseSVN, see the following page: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-copy.html
You seem to be looking for pass-by-reference, to do that make your function look this way (note the ampersand):
function foo(&$array)
{
$array[3]=$array[0]+$array[1]+$array[2];
}
Alternately, you can assign the return value of the function to a variable:
function foo($array)
{
$array[3]=$array[0]+$array[1]+$array[2];
return $array;
}
$waffles = foo($waffles)
on android devices using chrome we can't detect a backspace. You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
Have a look at the WebRequestHandler Class and its ServerCertificateValidationCallback Property:
using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback = ...
using (var client = new HttpClient(handler))
{
...
}
}
Try this
/.*[^a]$/
The []
denotes a character class, and the ^
inverts the character class to match everything but an a
.
Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.
There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.
That said, Objective-C and Swift really are not too scary...
2016 edit
Javascript with NativeScript framework is available to use now.
Code :
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie =
'username=' + value +
'; expires=' + now.toUTCString() +
'; path=/';
This isn't mentioned in any of the other answers. If you want a value that orms (should) hydrate as boolean you can use
CONVERT(bit, 0) -- false CONVERT(bit, 1) -- true
This gives you a bit which is not a boolean. You cannot use that value in an if statement for example:
IF CONVERT(bit, 0)
BEGIN
print 'Yay'
END
woudl not parse. You would still need to write
IF CONVERT(bit, 0) = 0
So its not terribly useful.
Here's a video and explaination how to use Instruments and NSZombie to find and fix memory crashes on iOS: http://www.markj.net/iphone-memory-debug-nszombie/
class expression can be used for simplicity.
// Foo.js
'use strict';
// export default class Foo {}
module.exports = class Foo {}
-
// main.js
'use strict';
const Foo = require('./Foo.js');
let Bar = new class extends Foo {
constructor() {
super();
this.name = 'bar';
}
}
console.log(Bar.name);
You can do it using xml.
Create an xml layout and name it like my_edit_text_border.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:radius="5dp" />
<stroke
android:width="2dp"
android:color="#949494"
/>
</shape>
</item>
</selector>
Add background to your Edittext
<EditText
android:id="@+id/editText1"
..
android:background="@layout/my_edit_text_border">
try this..
<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>
Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:
import sys
class StdoutRedirection:
"""Standard output redirection context manager"""
def __init__(self, path):
self._path = path
def __enter__(self):
sys.stdout = open(self._path, mode="w")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = sys.__stdout__
and then:
with StdoutRedirection("path/to/file"):
print("Hello world")
Also it would be really easy to add some functionality to StdoutRedirection
class (e.g. a method that lets you change the path)
Based on Thinker's answer, but allows duplicates.
The map increments map values as they appear, and decrements them if they are in the other array.
Any leftover will be included in the difference.
function diff(curr, prev) {_x000D_
let a = curr.split('').sort(), b = prev.split('').sort(), c = arrDiff(a, b);_x000D_
console.log(JSON.stringify(a), '-', JSON.stringify(b), '=', JSON.stringify(c));_x000D_
return c;_x000D_
}_x000D_
_x000D_
function arrDiff(larger, smaller) {_x000D_
var entries = {};_x000D_
for (var i = 0; i < larger.length; i++) {_x000D_
entries[larger[i]] = (entries[larger[i]] || 0) + 1;_x000D_
}_x000D_
for (var i = 0; i < smaller.length; i++) {_x000D_
if (entries[smaller[i]]) {_x000D_
entries[smaller[i]] -= 1;_x000D_
} else {_x000D_
entries[smaller[i]] = (entries[smaller[i]] || 0) + 1;_x000D_
}_x000D_
}_x000D_
return Object.keys(entries).sort().reduce((diff, key) => {_x000D_
if (entries[key] > 0) {_x000D_
for (var i = 0; i < entries[key]; i++) {_x000D_
diff.push(key);_x000D_
}_x000D_
}_x000D_
return diff;_x000D_
}, []);_x000D_
}_x000D_
_x000D_
// Smaller is a subset of Larger_x000D_
console.log('Result:', JSON.stringify(diff('ENLIGHTEN', 'LENGTHEN'))); // [ I ]_x000D_
console.log('Result:', JSON.stringify(diff('STRENGTH', 'TENTHS'))); // [ G, R ]_x000D_
_x000D_
// Both have a unique value_x000D_
console.log('Result:', JSON.stringify(diff('BUBBLE', 'RUBBLE'))); // [ B, R ]
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
I am using Ember (version 1.7.1) and I needed to both bind the value of the input and have a placeholder that was a FontAwesome icon. The only way to bind the value in Ember (that I know of) is to use the built in helper. But that causes the placeholder to be escaped, "" just shows up just like that, text.
If you are using Ember or not, you need to set the CSS of the input's placeholder to have a font-family of FontAwesome. This is SCSS (using Bourbon for the placeholder styling):
input {
width:96%;
margin:5px 2%;
padding:0 8px;
border:1px solid #444;
border-radius: 14px;
background: #fff;
@include placeholder {
font-family: 'FontAwesome', $gotham;
}
}
If you are just using handlebars, as has been mentioned before you can just set the html entity as the placeholder:
<input id="listFilter" placeholder="" type="text">
If you are using Ember bind the placeholder to a controller property that has the unicode value.
in the template:
{{text-field
id="listFilter"
placeholder=listFilterPlaceholder
value=listFilter}}
on the controller:
listFilter: null,
listFilterPlaceholder: "\uf002"
And the value binding works fine!
It will have already gone back before it executes the reload.
You would be better off to replace:
window.history.back();
location.reload();
with:
window.location.replace("pagehere.html");
This will return true if String only contains ASCII characters and false when it does not
Charset.forName("US-ASCII").newEncoder().canEncode(str)
If You want to remove non ASCII , here is the snippet:
if(!Charset.forName("US-ASCII").newEncoder().canEncode(str)) {
str = str.replaceAll("[^\\p{ASCII}]", "");
}
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r")
, if write than file = open("File.txt","w")
. You need to give the right permission regarding your usage.
more modes:
There is no simple way to do this, you basically need to subclass UITabBar and implement custom drawing to do what you want. It is quite a bit of work for the effect, but it may be worth it. I recommend filing a bug with Apple to get it added to a future iPhone SDK.
Here is how I scale <img> tags. If you want to make it a background image you can set it's position to absolute, place the image where you want (using the: top, bottom, left, right declarations), and set it's z-index below the rest of your page.
//simple example .your_class_name { width: 100%; height:auto; }
//background image example .your_background_class_name { width: 100%; height:auto; top: 0px; left: 0px; z-index: -1; position: absolute; }
To implement this you would simply place an image tag inside the data-role="page" element of your page(s) that has the ".your_background_class_name" class and the src attribute set to the image you want to have as your background.
I hope this helps.
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
So any of the following would suffice:
Object
and returning new Object()
or null
Void
and returning null
NullObject
of yoursYou can't make this method void
, and anything else returns something. Since that something is ignored, you can return anything.
payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:
https://s3-<region>.amazonaws.com/your.domain.com/some/asset
Where <region>
is the bucket location name. For example, if your bucket is in the us-west-2
(Oregon) region, you can do this:
https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset
One important reason for using constructor initializer list which is not mentioned in answers here is initialization of base class.
As per the order of construction, base class should be constructed before child class. Without constructor initializer list, this is possible if your base class has default constructor which will be called just before entering the constructor of child class.
But, if your base class has only parameterized constructor, then you must use constructor initializer list to ensure that your base class is initialized before child class.
Initialization of Subobjects which only have parameterized constructors
Efficiency
Using constructor initializer list, you initialize your data members to exact state which you need in your code rather than first initializing them to their default state & then changing their state to the one you need in your code.
If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.
Reference data members must be intialized when compiler enters constructor as references can't be just declared & initialized later. This is possible only with constructor initializer list.
Using the approach described in Fabio Iotti's answer I have created a more generic solution:
public abstract class ValidatedTextBox : TextBox {
private string m_lastText = string.Empty;
protected abstract bool IsValid(string text);
protected sealed override void OnTextChanged(EventArgs e) {
if (!IsValid(Text)) {
var pos = SelectionStart - Text.Length + m_lastText.Length;
Text = m_lastText;
SelectionStart = Math.Max(0, pos);
}
m_lastText = Text;
base.OnTextChanged(e);
}
}
"ValidatedTextBox", which contains all nontrivial validation behavior. All that's left to do is inherit from this class and override "IsValid" method with whatever validation logic is required. For example, using this class, it is possible to create "RegexedTextBox" which will accept only strings which match specific regular expression:
public abstract class RegexedTextBox : ValidatedTextBox {
private readonly Regex m_regex;
protected RegexedTextBox(string regExpString) {
m_regex = new Regex(regExpString);
}
protected override bool IsValid(string text) {
return m_regex.IsMatch(Text);
}
}
After that, inheriting from the "RegexedTextBox" class, we can easily create "PositiveNumberTextBox" and "PositiveFloatingPointNumberTextBox" controls:
public sealed class PositiveNumberTextBox : RegexedTextBox {
public PositiveNumberTextBox() : base(@"^\d*$") { }
}
public sealed class PositiveFloatingPointNumberTextBox : RegexedTextBox {
public PositiveFloatingPointNumberTextBox()
: base(@"^(\d+\" + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + @")?\d*$") { }
}
This occurs due to the availability of the previous version of the Application, that is not installed on the device but its data is present in the device memory. So it fails to upgrade this uninstalled application data on the device
Try this :
Go to Device Settings ==> Apps(All Apps) ==> search your App OR search for 'client' ==> In App info screen , press the triple dots option on top right corner ==> select 'Uninstall for All Users' ==> a promt appears select 'OK'
It works for me every time this error occurs
For me, I had simply forgotten to enter the actual domain name in the "Key Settings" area where it says Domains (one per line).
With Apache Commons IO you can do this in one line.
IOUtils.toString(request.getReader())
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
Building upon your existing Student class, this is how I usually do it, especially if I need more than one comparator.
public class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ":" + age;
}
@Override
public int compareTo(Student o) {
return Comparators.NAME.compare(this, o);
}
public static class Comparators {
public static Comparator<Student> NAME = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
};
public static Comparator<Student> AGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
};
public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int i = o1.name.compareTo(o2.name);
if (i == 0) {
i = o1.age - o2.age;
}
return i;
}
};
}
}
Usage:
List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);
EDIT
Since the release of Java 8 the inner class Comparators
may be greatly simplified using lambdas. Java 8 also introduces a new method for the Comparator
object thenComparing
, which removes the need for doing manual checking of each comparator when nesting them. Below is the Java 8 implementation of the Student.Comparators
class with these changes taken into account.
public static class Comparators {
public static final Comparator<Student> NAME = (Student o1, Student o2) -> o1.name.compareTo(o2.name);
public static final Comparator<Student> AGE = (Student o1, Student o2) -> Integer.compare(o1.age, o2.age);
public static final Comparator<Student> NAMEANDAGE = (Student o1, Student o2) -> NAME.thenComparing(AGE).compare(o1, o2);
}
This has become very easy with Jackson 2.0 and the Joda module.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.1.1</version>
</dependency>
Code and documentation: https://github.com/FasterXML/jackson-datatype-joda
Binaries: http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/
I don't know if this applies to JAX-WS, but for JAX-RS I was able to access a file by injecting a ServletContext and then calling getResourceAsStream() on it:
@Context ServletContext servletContext;
...
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");
Note that, at least in GlassFish 3.1, the path had to be absolute, i.e., start with slash. More here: How do I use a properties file with jax-rs?
If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)
@{
// implicit type
var something1 = "something";
// explicit type
string something2 = "something";
}
<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
If you're using the Web Publish feature in IIS, then the solution I found was to edit the publish configuration and remove the Destination URL
from the configuration (leave it blank).
If this is defined, then every time you publish the project it will open the URL specified in the Destination URL
(which is a redirect URL).
Reference: https://support.winhost.com/kb/a1604/visual-studio-publish-web-deploy.aspx
For my case, I have a dropdown list in my div container, so I can not use overflow: hidden
or my dropdown list will be hidden.
Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752
I use border-bottom-left-radius
and border-bottom-right-radius
in the child element to fix this issue.
make sure you add it the correct value for each child separately
iOS 10 and later
Works with all versions. Pass entity name and iterate through to delete all the entries and save the context.
func deleteData(entityToFetch: String, completion: @escaping(_ returned: Bool) ->()) {
let context = NSManagedObjectContext()
context = your managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityToFetch, in: context)
fetchRequest.includesPropertyValues = false
do {
let results = try context.fetch(fetchRequest) as! [NSManagedObject]
for result in results {
context.delete(result)
}
try context.save()
completion(true)
} catch {
completion(false)
print("fetch error -\(error.localizedDescription)")
}
}
If you happen to use glibmm you can try Glib::file_get_contents.
#include <iostream>
#include <glibmm.h>
int main() {
auto filename = "my-file.txt";
try {
std::string contents = Glib::file_get_contents(filename);
std::cout << "File data:\n" << contents << std::endl;
catch (const Glib::FileError& e) {
std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
}
return 0;
}
In C++, nested classes are not connected to any instance of the outer class. If you want bar
to access non-static members of foo
, then bar
needs to have access to an instance of foo
. Maybe something like:
class bar {
public:
int getA(foo & f ) {return foo.a;}
};
Or maybe
class bar {
private:
foo & f;
public:
bar(foo & g)
: f(g)
{
}
int getA() { return f.a; }
};
In any case, you need to explicitly make sure you have access to an instance of foo
.
Yet another solution: set the timeout in the jest config file, e.g.:
{ // ... other stuff here
"testTimeout": 90000
}
I believe this will only appear when running the page locally in this particular case, i.e. you should not see this when loading the apge from a web server.
However if you have permission to do so, you could turn off the prompt for Internet Explorer by following Tools (menu) → Internet Options → Security (tab) → Custom Level (button) → and Disable Automatic prompting for ActiveX controls.
This will of course, only affect your browser.
$ irb --simple-prompt
class TestClass
def method1
end
def method2
end
def method3
end
end
tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3
VS2019->View->Other Windows->Command Window
(CTRL+ALT+A)
Tools.DiffFiles File1 File2
Change your FirstyActivity to:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
btn_go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
MainActivity.this,
MainActivity2.class);
startActivity(i);
}
}
});
}
Hope it will help you.
There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.
However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.
I know this is an oldish question but I found it whilst looking for the same solution. The solution above doesn't appear to work in Laravel 4, you can however use this now:
<a href="{{ URL::previous() }}">Go Back</a>
Hope this helps people who look for this feature in L4
(Source: https://github.com/laravel/framework/pull/501/commits)
try this:
var hasVScroll = document.body.scrollHeight > document.body.clientHeight;
This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll
variable will contain true or false.
If you need to do a more thorough check, add the following to the code above:
// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");
// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible"
|| cStyle.overflowY == "visible"
|| (hasVScroll && cStyle.overflow == "auto")
|| (hasVScroll && cStyle.overflowY == "auto");
List and Set both are interfaces. They both extends Collection interface. The important differences between set and list are:
The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates.
List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.
Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion order).
List allows any number of null elements. Set can have only a single null elements at most.
Had the same question. The other answers don't seem to address why close() is really necessary? Also, Op seemed to be struggling to figure out the preferred way to work with HttpClient, et al.
According to Apache:
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
In addition, the relationships go as follows:
HttpClient
(interface)implemented by:
CloseableHttpClient
- ThreadSafe.
DefaultHttpClient
- ThreadSafe BUT deprecated, useHttpClientBuilder
instead.
HttpClientBuilder
- NOT ThreadSafe, BUT creates ThreadSafeCloseableHttpClient
.
- Use to create CUSTOM
CloseableHttpClient
.
HttpClients
- NOT ThreadSafe, BUT creates ThreadSafeCloseableHttpClient
.
- Use to create DEFAULT or MINIMAL
CloseableHttpClient
.
The preferred way according to Apache:
CloseableHttpClient httpclient = HttpClients.createDefault();
The example they give does httpclient.close()
in the finally
clause, and also makes use of ResponseHandler
as well.
As an alternative, the way mkyong does it is a bit interesting, as well:
HttpClient client = HttpClientBuilder.create().build();
He doesn't show a client.close()
call but I would think it is necessary, since client
is still an instance of CloseableHttpClient
.
Please, please, and pretty please do not try this at home, or work, or anywhere really.
This is a way solve to a very very specific problem, and I hope you will not have that.
I'm posting this since it is technically an answer, and another perspective to look at it.
I repeat, do not use it under any condition. Code is to run with LINQPad.
void Main()
{
(new A(1)).Dump();
(new B(2, -1)).Dump();
var b2 = new B(2, -1);
b2.Increment();
b2.Dump();
}
class A
{
public readonly int I = 0;
public A(int i)
{
I = i;
}
}
class B: A
{
public int J;
public B(int i, int j): base(i)
{
J = j;
}
public B(int i, bool wtf): base(i)
{
}
public void Increment()
{
int i = I + 1;
var t = typeof(B).BaseType;
var ctor = t.GetConstructors().First();
ctor.Invoke(this, new object[] { i });
}
}
Since constructor is a method, you can call it with reflection. Now you either think with portals, or visualize a picture of a can of worms. sorry about this.
You can use the BytesIO
class to get a wrapper around strings that behaves like a file. The BytesIO
object provides the same interface as a file, but saves the contents just in memory:
import io
with io.BytesIO() as output:
image.save(output, format="GIF")
contents = output.getvalue()
You have to explicitly specify the output format with the format
parameter, otherwise PIL will raise an error when trying to automatically detect it.
If you loaded the image from a file it has a format
parameter that contains the original file format, so in this case you can use format=image.format
.
In old Python 2 versions before introduction of the io
module you would have used the StringIO
module instead.
select index_name, column_name
from user_ind_columns
where table_name = 'NAME';
OR use this:
select TABLE_NAME, OWNER
from SYS.ALL_TABLES
order by OWNER, TABLE_NAME
And for Indexes:
select INDEX_NAME, TABLE_NAME, TABLE_OWNER
from SYS.ALL_INDEXES
order by TABLE_OWNER, TABLE_NAME, INDEX_NAME
For some reason, adding the environment variable didn't work for me.
I was able to specify a path to Firefox in the command line node configuration, as described on this page (grid2).
-browser “browserName=firefox,version=3.6,firefox_binary=c:\Program Files\Mozilla Firefox\firefox.exe ,maxInstances=3, platform=WINDOWS”
just use CustomEvent
Node.prototype.fire=function(type,options){
var event=new CustomEvent(type);
for(var p in options){
event[p]=options[p];
}
this.dispatchEvent(event);
}
4 ex want to simulate ctrl+z
window.addEventListener("keyup",function(ev){
if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
})
document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})
You can simply convert the given number using Number primitive type in JavaScript as shown below.
var c = Number(first) + Number(second);
You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
It's a C heritage, in C, if you do :
enum TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
};
you'll have to use it doing something like :
enum TokenType foo;
But if you do this :
typedef enum e_TokenType
{
blah1 = 0x00000000,
blah2 = 0X01000000,
blah3 = 0X02000000
} TokenType;
You'll be able to declare :
TokenType foo;
But in C++, you can use only the former definition and use it as if it were in a C typedef.
This is about as late compared to the guy who said he was late as he was to the original answer, but in my case (MySQL via WAMP on Windows 7), I had to use:
--skip-lock-tables
We can use splatting for this:
& $command @args
where @args
(automatic variable $args) is splatted into array of parameters.
Under PS, 5.1
One thing bothering me with default parameters is that you can't specify the last parameters but use the default values for the first ones. For example, in your code, you can't create a Foo with no name but a given age (however, if I remember correctly, this will be possible in C++0x, with the unified constructing syntax). Sometimes, this makes sense, but it can also be really awkward.
In my opinion, there is no rule of thumb. Personnaly, I tend to use multiple overloaded constructors (or methods), except if only the last argument needs a default value.
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use
$(document).ready(function() {
$('#createFormId').on('show.bs.modal', function(event) {
$("#cafeId").val($(event.relatedTarget).data('id'));
});
});
Couldn't you just pass the arguments
array along?
function mainfunc (func){
// remove the first argument containing the function name
arguments.shift();
window[func].apply(null, arguments);
}
function calledfunc1(args){
// Do stuff here
}
function calledfunc2(args){
// Do stuff here
}
mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');
Perform the following steps:
regedit
in the Run window.HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
.You should return only one column and one row in the where query where you assign the returned value to a variable. Example:
select * from table1 where Date in (select * from Dates) -- Wrong
select * from table1 where Date in (select Column1,Column2 from Dates) -- Wrong
select * from table1 where Date in (select Column1 from Dates) -- OK
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
The below packages are also helps you,
yum install gcc glibc glibc-common gd gd-devel -y
sendStickyBroadcast()
performs a sendBroadcast(Intent)
known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)
. In all other ways, this behaves the same as sendBroadcast(Intent)
. One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action -- even with a null BroadcastReceiver
-- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Give the first div float: left;
and a fixed width, and give the second div width: 100%;
and float: left;
. That should do the trick. If you want to place items below it you need a clear: both;
on the item you want to place below it.
If you're using a virtualenv, make sure that you are running pip from within the virtualenv.
$ which pip
/Library/Frameworks/Python.framework/Versions/Current/bin/pip
$ find . -name pip -print
./flask/bin/pip
./flask/lib/python2.7/site-packages/pip
$ ./flask/bin/pip install python-dateutil
Here is another way to implement SilentGhost's original suggestion:
def dict2obj(d):
if isinstance(d, dict):
n = {}
for item in d:
if isinstance(d[item], dict):
n[item] = dict2obj(d[item])
elif isinstance(d[item], (list, tuple)):
n[item] = [dict2obj(elem) for elem in d[item]]
else:
n[item] = d[item]
return type('obj_from_dict', (object,), n)
else:
return d
Essentially you want to add code to the Calculate
event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.
In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:
To be short, in the case of cross domain request, the browser automatically adds an Origin
header in the request. There are two cases:
text/plain
, application/x-www-form-urlencoded
and multipart/form-data
.So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin
one.
200 OK HTTP/1.1
(...)
Access-Control-Allow-Origin: *
To debug such issues, you can use developer tools within browsers (Network tab).
Regarding Angular2, simply use the Http
object like any other requests (same domain for example):
return this.http.get('https://angular2.apispark.net/v1/companies/')
.map(res => res.json()).subscribe(
...
);
The Java language specification says you can have return with no expression if your method returns void.
To expand upon Mr. Eels comment, you can do it like this:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't say we ain't good to ya!
The accepted answer (the one with the green check mark) has an issue.
The problem:
var result = Lists.Repeated(new MyType(), sizeOfList);
// each item in the list references the same MyType() object
// if you edit item 1 in the list, you are also editing item 2 in the list
I recommend changing the line above to perform a copy of the object. There are many different articles about that:
If you want to initialize every item in your list with the default constructor, rather than NULL, then add the following method:
public static List<T> RepeatedDefaultInstance<T>(int count)
{
List<T> ret = new List<T>(count);
for (var i = 0; i < count; i++)
{
ret.Add((T)Activator.CreateInstance(typeof(T)));
}
return ret;
}
PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "DomainName", UserAccountOU, UserName, Password);
UserPrincipal UserPrincipalID = UserPrincipal.FindByIdentity(pc1, IdentityType.SamAccountName, UserID);
searcher.Filter = "(&(ObjectClass=group)(member = " + UserPrincipalID.DistinguishedName + "));
BCP can dump your data to a file and in SQL Server Management Studio, right click on the table, and select "script table as" then "create to", then "file..." and it will produce a complete table script.
BCP info
https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=319
http://msdn.microsoft.com/en-us/library/aa174646%28SQL.80%29.aspx
Go to File | Settings | Build, Execution, Deployment | Build Tools | Maven
Select "Always update snapshots"
You probably want the answer to "How to call an external command in Python".
The simplest approach is to use the os.system
function, e.g.:
import os
os.system("some_command &")
Basically, whatever you pass to the system
function will be executed the same as if you'd passed it to the shell in a script.
Didnt work for me.
I created a new key and string value and managed to get it working
Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
If your application theme is AppTheme(or anything else), then in styles.xml add the following code:
<style name="HiddenTitleTheme" parent="AppTheme">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
Then in manifest file add the following in the activity tag for which you want to disable activity label:
android:theme="@style/HiddenTitleTheme"
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
If you are looking to count the number of NAs in the entire dataframe you could also use
sum(is.na(df))
Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:
Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)
Sign the application using your keystore and the jarsigner tool (follow below steps):
Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"
Now enter belwo command in cmd:
jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias
It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:
jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk
It should come back with: jar verified.
Method 2
If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.
These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.
Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero
):
if (!$result['column']>0){
}
Found out that this breaks some applications, the better way to do it is
In addition to symlink, on more recent distros and filesystems, as root you can also use bind-mount:
mkdir /home/username
mount --bind --verbose /extra-home/username /home/username
This is useful for allowing access "through" the /home directory to subdirs via daemons that are otherwise configured to avoid pathing through symlinks (apache, ftpd, etc.).
You have to remember (or init script) to bind upon restarts, of course.
An example init script in /etc/fstab
is
/extra-home/username /home/username none defaults,bind 0 0
Here's a small script implementing this feature (inspired by the Shea Frederick blog article that Kyle mentions):
I'm new to R as well and faced the exact same problem. But then I looked at my data and noticed that it is being caused due to the fact that my csv file was using a comma separator (,) in all numeric columns (Ex: 1,233,444.56 instead of 1233444.56).
I removed the comma separator in my csv file and then reloaded into R. My data frame now recognises all columns as numbers.
I'm sure there's a way to handle this within the read.csv function itself.
This wrapper method will help :
private static JSONObject merge(JSONObject... jsonObjects) throws JSONException {
JSONObject jsonObject = new JSONObject();
for(JSONObject temp : jsonObjects){
Iterator<String> keys = temp.keys();
while(keys.hasNext()){
String key = keys.next();
jsonObject.put(key, temp.get(key));
}
}
return jsonObject;
}
None of the above solutions worked for me (dotnetcore 1.1, VS2017). Here's what fixed it:
Microsoft.TestPlatform.TestHost
Microsoft.NET.Test.Sdk
Those are in addition to these packages I installed prior:
With the new (yet in Editor's draft) CSS 4 properties you can achieve this by using min()
and max()
(also you can use clamp()
as a - kind of - shorthand for both min()
and max()
clamp(MIN, VAL, MAX)
is resolved asmax(MIN, min(VAL, MAX))
min()
syntax:
min( <calc-sum># ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
max()
syntax:
max( <calc-sum># ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
clamp()
syntax:
clamp( <calc-sum>#{3} ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
.min {
/* demo */
border: green dashed 5px;
/*this your min padding-left*/
padding-left: min(50vw, 50px);
}
.max {
/* demo */
border: blue solid 5px;
/*this your max padding-left*/
padding-left: max(50vw, 500px);
}
.clamp {
/* demo */
border: red dotted 5px;
/*this your clamp padding-left*/
padding-left: clamp(50vw, 70vw, 1000px);
}
/* demo */
* {
box-sizing: border-box
}
section {
width: 50vw;
}
div {
height: 100px
}
/* end of demo */
_x000D_
<section>
<div class="min"></div>
<div class="max"></div>
<div class="clamp"></div>
</section>
_x000D_
No you can't.
margin
and padding
properties don't have the min
/max
prefixes
An approximately way would be using relative units (vh
/vw
), but still not min/max
And as @vigilante_stark pointed out in the answer, the CSS calc()
function could be another workaround, something like these:
/* demo */
* {
box-sizing: border-box
}
section {
background-color: red;
width: 50vw;
height: 50px;
position: relative;
}
div {
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0
}
/* end of demo */
.min {
/* demo */
border: green dashed 4px;
/*this your min padding-left*/
padding-left: calc(50vw + 50px);
}
.max {
/* demo */
border: blue solid 3px;
/*this your max padding-left*/
padding-left: calc(50vw + 200px);
}
_x000D_
<section>
<div class="min"></div>
<div class="max"></div>
</section>
_x000D_
Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.
Typically these are development related libraries and the most common use of these tools is for developers working on osx.
They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.
xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).
macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.
One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.
homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.
macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects
Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in
/opt/local
Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.
Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:
We really don’t like dupes in Homebrew/homebrew
However, we do like dupes in the tap!
Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:
- Duplicate libraries regularly break builds
- Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
- We want you to try harder to make your formula work with what OS X comes with
You can optionally overwrite the macosx supplied versions of utilities with homebrew.
What helped me was deleting my target folder and recompile my project again. This problem occured to me when I used a second server for my tests that needed a server running. Conclusion: delete your target file when you make big changes to the war file.
This should work pretty nicely. It will never grow beyond the initial size. The toList method will give you the entries in the correct chronological order. This was done in groovy - but converting it to java proper should be pretty easy.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
List<T> list = new ArrayList<>()
int oldest = (cur == size - 1) ? 0 : cur
for (int i = 0; i < this.entries.length; i++) {
def e = this.entries[oldest + i < size ? oldest + i : oldest + i - size]
if (e) list.add(e)
}
return list
}
}
FixedSizeCircularReference<String> latestEntries = new FixedSizeCircularReference(100)
latestEntries.add('message 1')
// .....
latestEntries.add('message 1000')
latestEntries.asList() //Returns list of '100' messages
throw
re-throws the caught exception, retaining the stack trace, while throw new Exception
loses some of the details of the caught exception.
You would normally use throw
by itself to log an exception without fully handling it at that point.
BlackWasp has a good article sufficiently titled Throwing Exceptions in C#.
Had the same problem but had to update a column with the id that was about to enter, so you can make an update should be done BEFORE and AFTER not BEFORE had no id so I did this trick
DELIMITER $$
DROP TRIGGER IF EXISTS `codigo_video`$$
CREATE TRIGGER `codigo_video` BEFORE INSERT ON `videos`
FOR EACH ROW BEGIN
DECLARE ultimo_id, proximo_id INT(11);
SELECT id INTO ultimo_id FROM videos ORDER BY id DESC LIMIT 1;
SET proximo_id = ultimo_id+1;
SET NEW.cassette = CONCAT(NEW.cassette, LPAD(proximo_id, 5, '0'));
END$$
DELIMITER ;
if you want to get the index position of the outliers idx_list
will return it.
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
data_range = np.arange(len(data))
idx_list = data_range[s>=m]
return data[s<m], idx_list
data_points = np.array([8, 10, 35, 17, 73, 77])
print(reject_outliers(data_points))
after rejection: [ 8 10 35 17], index positions of outliers: [4 5]
Pseudocode
var ifr = document.createElement('iframe');
var frm = document.createElement('form');
frm.setAttribute("action", "yoururl");
frm.setAttribute("method", "post");
// create hidden inputs, add them
// not shown, but similar (create, setAttribute, appendChild)
ifr.appendChild(frm);
document.body.appendChild(ifr);
frm.submit();
You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.
Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive TTYs. I needed this for old machines where I can't install Expect or add modules to Python.
Code:
(
echo 'scp [email protected]:./install.sh .'
sleep 5
echo 'scp-passwd'
sleep 5
echo 'exit'
) |
python -c 'import pty; pty.spawn("/usr/bin/bash")'
Output:
scp [email protected]:install.sh .
bash-4.2$ scp [email protected]:install.sh .
Password:
install.sh 100% 15KB 236.2KB/s 00:00
bash-4.2$ exit
exit
tl;dr:
commit()
writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation.apply()
schedules the data to be written asynchronously. It does not inform you about the success of the operation.apply()
and immediately read via any getX-method, the new value will be returned!apply()
at some point and it's still executing, any calls to commit()
will block until all past apply-calls and the current commit-call are finished.More in-depth information from the SharedPreferences.Editor Documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.
The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.
We can use FlexBox for Sticky Footer and Header without using POSITIONS in CSS.
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #037cf5;_x000D_
}_x000D_
_x000D_
footer {_x000D_
height: 50px;_x000D_
flex-shrink: 0;_x000D_
background-color: #134c7d;_x000D_
}_x000D_
_x000D_
main {_x000D_
flex: 1 0 auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<header>HEADER</header>_x000D_
<main class="content">_x000D_
_x000D_
</main>_x000D_
<footer>FOOTER</footer>_x000D_
</div>
_x000D_
DEMO - JSFiddle
Note : Check browser supports for FlexBox. caniuse
You can easily enable debugging support using an option for the @EnableWebSecurity annotation:
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
If you need profile-specific control the in your application-{profile}.properties file
org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false
Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/
chart.series[0].setData(data,true);
The setData
method itself will call the redraw method
It works only if the frame contains page from the same domain (does not violate same-origin policy)
See this:
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
Unless you tell the development server that it's running in development mode, it will assume you're using it in production and warn you not to. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.
Enable development mode by setting the FLASK_ENV
environment variable to development
.
$ export FLASK_APP=example
$ export FLASK_ENV=development
$ flask run
If you're running in PyCharm (or probably any other IDE) you can set environment variables in the run configuration.
Development mode enables the debugger and reloader by default. If you don't want these, pass --no-debugger
or --no-reloader
to the run
command.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
if (bytes != null)
for (byte b:bytes) {
final String hexString = Integer.toHexString(b & 0xff);
if(hexString.length()==1)
sb.append('0');
sb.append(hexString);//.append(' ');
}
return sb.toString();//.toUpperCase();
}
I found a nice solution on the blog of Lisa Wray. With the new data binding it is possible to set the font in your XML files.
@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}
In XML:
<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
In practice, POST works well for creating resources. The URL of the newly created resource should be returned in the Location response header. PUT should be used for updating a resource completely. Please understand that these are the best practices when designing a RESTful API. HTTP specification as such does not restrict using PUT/POST with a few restrictions for creating/updating resources. Take a look at http://techoctave.com/c7/posts/71-twitter-rest-api-dissected that summarizes the best practices.
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
print_r pretty print for PHP
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array($elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
if(is_array($elem)){
echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
}else{
echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#888888":"#BBBBBB";
}else{
$rgb=($color++%2)?"#8888BB":"#BBBBFF";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
import time
import datetime
# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
start = end - datetime.timedelta(days=numdays+1)
end = int(time.mktime(end.timetuple()))
start = int(time.mktime(start.timetuple()))
# 86400 s = 1 day
return xrange(start, end, 86400)
# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
print datetime.datetime.fromtimestamp(dt).date()
You can do it in a simpler way using the DialogResult.cancel
method.
Eg:
Dim anInput as String = InputBox("Enter your pin")
If anInput <>"" then
' Do something
Elseif DialogResult.Cancel then
Msgbox("You've canceled")
End if
None of the other answers worked for me. After some tinkering I unsinstalled sklearn:
pip uninstall sklearn
Then I removed sklearn folder from here: (adjust the path to your system and python version)
C:\Users\%USERNAME%\AppData\Roaming\Python\Python36\site-packages
And the installed it from wheel from this site: link
The error was there probably because of a version conflict with sklearn installed somewhere else.
Are the days of passing const std::string & as a parameter over?
No. Many people take this advice (including Dave Abrahams) beyond the domain it applies to, and simplify it to apply to all std::string
parameters -- Always passing std::string
by value is not a "best practice" for any and all arbitrary parameters and applications because the optimizations these talks/articles focus on apply only to a restricted set of cases.
If you're returning a value, mutating the parameter, or taking the value, then passing by value could save expensive copying and offer syntactical convenience.
As ever, passing by const reference saves much copying when you don't need a copy.
Now to the specific example:
However inval is still quite a lot larger than the size of a reference (which is usually implemented as a pointer). This is because a std::string has various components including a pointer into the heap and a member char[] for short string optimization. So it seems to me that passing by reference is still a good idea. Can anyone explain why Herb might have said this?
If stack size is a concern (and assuming this is not inlined/optimized), return_val
+ inval
> return_val
-- IOW, peak stack usage can be reduced by passing by value here (note: oversimplification of ABIs). Meanwhile, passing by const reference can disable the optimizations. The primary reason here is not to avoid stack growth, but to ensure the optimization can be performed where it is applicable.
The days of passing by const reference aren't over -- the rules just more complicated than they once were. If performance is important, you'll be wise to consider how you pass these types, based on the details you use in your implementations.
I could reproduce this issue by creating an enumeration with a non-static member class and a static block enumerating its values:
public enum Foo {
Dummy(new Bar [] {new Bar()});
static {
for (Foo foo: Foo.values());
}
private Foo(Bar [] params) {}
public class Bar {}
}
This class breaks the Ganymede compiler. If you delete the line in the static initializer block, the code compiles correctly again, and you get the error that there is no enclosing instance for the new Bar() call, as expected.
-- correction: The above holds only if the project has gaeNature from Google Appengine. However, if you get an error similar as mentioned in the original question, you might be encountering another java compiler bug ...
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
What helped me in case of Android Studio: The problem occurred after renamning package of large project. So I did almost everything AS offers to clean and refresh the project officially, and it works. I'm not saying this is solution for everyone just in case you're using Android Studio. Done in Android Studio 3.5.1, Windows 10.
You can use this in LinearLayout
:
android:divider="?android:dividerHorizontal"
android:showDividers="middle"
For Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="?android:dividerHorizontal"
android:showDividers="middle"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd gttff hthjj ssrt guj"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd gttff hthjj ssrt guj"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd"/>
</LinearLayout>
I had the same problem, tnsnames.ora
worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.
It turns out that the database was caching backup copies of tnsnames.ora
like tnsnames.ora.bk2
, tnsnames09042811AM4501.bak
, tnsnames.ora.bk
etc. These files were not readable by the average user.
I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.
The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.
Because thats coding convention. See here for more.
Put the table in the second image on Sheet2, columns D to F.
In Sheet1, cell D2 use the formula
=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
copy across and down.
Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
You may also be interested in the write-up from Sun, as part of the standard JSSE documentation:
http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#Stores
Typically, the trust store is used to store only public keys, for verification purposes, such as with X.509 authentication. For manageability purposes, it's quite common for admins or developers to simply conflate the two into a single store.
In my opinion, turning off the -e
option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e
Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.
If you have a line in your script where failure is expected, like a grep or a find, then just add || true
to the end of that line. That ensures that line will always return success.
If you need to use that exit code, you can either hoist the command into your if statement:
grep foo bar; if [ $? == 0 ]; then ... --> if grep foo bar; then ...
Or you can capture the return code in your ||
clause:
grep foo bar || ret=$?
It is not so much that C is fast as that C's cost model is transparent. If a C program is slow, it is slow in an obvious way: by executing a lot of statements. Compared with the cost of operations in C, high-level operations on objects (especially reflection) or strings can have costs that are not obvious.
Two languages that generally compile to binaries which are just as fast as C are Standard ML (using the MLton compiler) and Objective Caml. If you check out the benchmarks game you'll find that for some benchmarks, like binary trees, the OCaml version is faster than C. (I didn't find any MLton entries.) But don't take the shootout too seriously; it is, as it says, a game, the the results often reflect how much effort people have put in tuning the code.
None of the above worked for me. But yarn install
worked, then npm i
started working. Not sure what yarn fixed, but quick and easy solution!
calling bean action from a will be a good idea,keep attribute autoRun="true" example below
<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />
This is happening because the WC_Customer abstract doesn't hold hold address data (among other data) apart from within a session. This data is stored via the cart/checkout pages, but again—only in the session (as far as the WC_Customer class goes).
If you take a look at how the checkout page gets the customer data, you'll follow it to the WC_Checkout class method get_value
, which pulls it directly out of user meta. You'd do well to follow the same pattern :-)
For any javadoc (not just the ones available for download) you can use the DownThemAll addon for Firefox with a suitable renaming mask, for example:
*subdirs*/*name*.*ext*
https://addons.mozilla.org/en-us/firefox/addon/downthemall/
https://www.downthemall.org/main/install-it/downthemall-3-0-7/
Edit: It's possible to use some older versions of the DownThemAll add-on with Pale Moon browser.
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
Regular expressions with character classes (e.g. [[:digit:]]
) are not supported in the default regular expression syntax used by find
. You need to specify a different regex type such as posix-extended
in order to use them.
Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.
Why not Process.Start(@"c:\test");
?
I like to use a TreeWalker if the set of elements are children of a root node.
All the solutions so far were lacking of certain functionality. Here is my solution:
public class AttachedWebDriver extends RemoteWebDriver {
public AttachedWebDriver(URL url, String sessionId) {
super();
setSessionId(sessionId);
setCommandExecutor(new HttpCommandExecutor(url) {
@Override
public Response execute(Command command) throws IOException {
if (command.getName() != "newSession") {
return super.execute(command);
}
return super.execute(new Command(getSessionId(), "getCapabilities"));
}
});
startSession(new DesiredCapabilities());
}
}
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()
# if you want to return run itself to be used later
return theclass.run
Change the end of comm system to:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
python_test.py
import subprocess
a = subprocess.check_output("batch_1.bat")
print a
This gives output from batch file to be print on the python IDLE/running console. So in batch file you can echo the result in each step to debug the issue. This is also useful in automation when there is an error happening in the batch call, to understand and locate the error easily.(put "echo off" in batch file beginning to avoid printing everything)
batch_1.bat
echo off
echo "Hello World"
md newdir
echo "made new directory"
please use this code for input text
$('#search').on("input",function (e) {});
if you use .on("change",function (e) {});
then you need to blur input
if you use .on("keyup",function (e) {});
then you get value before the last character you typed
if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):
This will insert what is in TEXTO into the regex as a string.
Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind
I removed my JavaScript from the head section of page and added it to the body of the page and got it working
here is yhe full code to clone all repos from a given BitBucket team/user
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~
Little script to clone all repos from a given BitBucket team/user.
:author: https://thepythoncoding.blogspot.com/2019/06/python-script-to-clone-all-repositories.html
:copyright: (c) 2019
"""
from git import Repo
from requests.auth import HTTPBasicAuth
import argparse
import json
import os
import requests
import sys
def get_repos(username, password, team):
bitbucket_api_root = 'https://api.bitbucket.org/1.0/users/'
raw_request = requests.get(bitbucket_api_root + team, auth=HTTPBasicAuth(username, password))
dict_request = json.loads(raw_request.content.decode('utf-8'))
repos = dict_request['repositories']
return repos
def clone_all(repos):
i = 1
success_clone = 0
for repo in repos:
name = repo['name']
clone_path = os.path.abspath(os.path.join(full_path, name))
if os.path.exists(clone_path):
print('Skipping repo {} of {} because path {} exists'.format(i, len(repos), clone_path))
else:
# Folder name should be the repo's name
print('Cloning repo {} of {}. Repo name: {}'.format(i, len(repos), name))
try:
git_repo_loc = '[email protected]:{}/{}.git'.format(team, name)
Repo.clone_from(git_repo_loc, clone_path)
print('Cloning complete for repo {}'.format(name))
success_clone = success_clone + 1
except Exception as e:
print('Unable to clone repo {}. Reason: {} (exit code {})'.format(name, e.stderr, e.status))
i = i + 1
print('Successfully cloned {} out of {} repos'.format(success_clone, len(repos)))
parser = argparse.ArgumentParser(description='clooney - clone all repos from a given BitBucket team/user')
parser.add_argument('-f',
'--full-path',
dest='full_path',
required=False,
help='Full path of directory which will hold the cloned repos')
parser.add_argument('-u',
'--username',
dest="username",
required=True,
help='Bitbucket username')
parser.add_argument('-p',
'--password',
dest="password",
required=False,
help='Bitbucket password')
parser.add_argument('-t',
'--team',
dest="team",
required=False,
help='The target team/user')
parser.set_defaults(full_path='')
parser.set_defaults(password='')
parser.set_defaults(team='')
args = parser.parse_args()
username = args.username
password = args.password
full_path = args.full_path
team = args.team
if not team:
team = username
if __name__ == '__main__':
try:
print('Fetching repos...')
repos = get_repos(username, password, team)
print('Done: {} repos fetched'.format(len(repos)))
except Exception as e:
print('FATAL: Could not get repos: ({}). Terminating script.'.format(e))
sys.exit(1)
clone_all(repos)
More info: https://thepythoncoding.blogspot.com/2019/06/python-script-to-clone-all-repositories.html
I think you might see slightly better performance by doing it this way:
$("#Create, #Edit").find(".myClass").plugin(){
// Options
});
Here is a function that recursively calculates the binomial coefficients using conditional expressions
def binomial(n,k):
return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))
req.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
You can set MY_SOCKET_TIMEOUT_MS
as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES
can be 0 default is 1.
Cleaning the project solved my problem.
Steps: Product -> Clean(or Shift + Cmd + K)
Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".
Here is the code to mock this functionality using PowerMockito API.
Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);
You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
// your testing code
}
In general, the most appropriated way to avoid this problem, (also because of better Mockito integration in JUnit) is to use the Setter/Field Injection as described at https://www.baeldung.com/circular-dependencies-in-spring and at https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
@Component("bean1")
@Scope("view")
public class Bean1 {
private Bean2 bean2;
@Autowired
public void setBean2(Bean2 bean2) {
this.bean2 = bean2;
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
@Autowired
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
Here is the working sample fiddle
Just remove additional \r\n and "|" from your reg ex.
Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....
Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.
It would be more correct to say that stdin
, stdout
, and stderr
are "I/O streams" rather
than files. As you've noticed, these entities do not live in the filesystem. But the
Unix philosophy, as far as I/O is concerned, is "everything is a file". In practice,
that really means that you can use the same library functions and interfaces (printf
,
scanf
, read
, write
, select
, etc.) without worrying about whether the I/O stream
is connected to a keyboard, a disk file, a socket, a pipe, or some other I/O abstraction.
Most programs need to read input, write output, and log errors, so stdin
, stdout
,
and stderr
are predefined for you, as a programming convenience. This is only
a convention, and is not enforced by the operating system.
If you are from the Java world, you can compare a closure with a member function of a class. Look at this example
var f=function(){
var a=7;
var g=function(){
return a;
}
return g;
}
The function g
is a closure: g
closes a
in. So g
can be compared with a member function, a
can be compared with a class field, and the function f
with a class.
Since it wouldn't add any value to repeat that it means echo
, I thought you'd like to see what means in PHP exactly:
Array
(
[0] => Array
(
[0] => 368 // T_OPEN_TAG_WITH_ECHO
[1] => <?=
[2] => 1
)
[1] => Array
(
[0] => 309 // T_VARIABLE
[1] => $a
[2] => 1
)
[2] => ; // UNKNOWN (because it is optional (ignored))
[3] => Array
(
[0] => 369 // T_CLOSE_TAG
[1] => ?>
[2] => 1
)
)
You can use this code to test it yourself:
$tokens = token_get_all('<?=$a;?>');
print_r($tokens);
foreach($tokens as $token){
echo token_name((int) $token[0]), PHP_EOL;
}
From the List of Parser Tokens, here is what T_OPEN_TAG_WITH_ECHO links to.
Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....