Catching Exception
will catch a RuntimeException
i had everything what everyone above was saying and resolved the error by simply calling the
super.onCreate(savedInstanceState);
as first instruction in oncreate method; before it was last line in method. :|
wasted whole day.
For Ionic 4 Just
$ cordova clean
Helped me then run
$ ionic cordova run android --device
Try getParent()
at the argument place of context
like new AlertDialog.Builder(getParent());
Hope it will work, it worked for me.
Android Doc says -
FLAG_ACTIVITY_NEW_TASK requirement is now enforced
With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.
Note: The flag requirement has always been the intended behavior, and was enforced on versions lower than Android 7.0 (API level 24). A bug in Android 7.0 prevented the flag requirement from being enforced.
That means for (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK
while calling startActivity()
from outside of an Activity
context.
So it is better to add flag for all the versions -
...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
You have to add a MySQL jdbc driver to the classpath.
Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.
You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27
Android documents suggests to use getApplicationContext();
but it will not work instead of that use your current activity while instantiating AlertDialog.Builder or AlertDialog or Dialog...
Ex:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
or
AlertDialog.Builder builder = new AlertDialog.Builder((Your Activity).this);
you will have to instantiate it before you throw it
throw new RuntimeException(arg0)
PS: Intrestingly enough the Netbeans IDE should have already pointed out that compile time error
subclasses
of class RuntimeException
are unchecked exception.Exception
but not RuntimeException
are considered to be checked exceptions
.checked exception
.
throws
clause containing the checked-exception
.Exception
classes are defined to be checked when they are considered important enough to catch or declare.One Good solution is to restart the PC, this will make the right entry in the Registry of the PC. Restarting solves my problem
add xrange=range
in your code :) It works to me.
If you are extending ActionBarActivity in your MainActivity, you will have to change the parent theme in values-v11 also.
So the style.xml in values-v11 will be -
<!-- res/values-v11/themes.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="QueryTheme" parent="@style/Theme.AppCompat">
<!-- Any customizations for your app running on devices with Theme.Holo here -->
</style>
</resources>
EDIT: I would recommend you stop using ActionBar and start using the AppBar layout included in the Android Design Support Library
The error is self-explanatory... doInBackground()
runs on a background thread which, since it is not intended to loop, is not connected to a Looper
.
You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground()
implementation returns will be passed to onPostExecute()
which runs on the UI thread.
mActivity = ThisActivity.this;
mActivity.runOnUiThread(new Runnable() {
public void run() {
new asyncCreateText().execute();
}
});
ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:
Looks like you're trying to start an AsyncTask
from a GL rendering thread... don't do that cos they won't ever Looper.loop()
either. AsyncTasks are really designed to be run from the UI thread only.
The least disruptive fix would probably be to call Activity.runOnUiThread()
with a Runnable
that kicks off your AsyncTask
.
The regex below will match both numbers from your example.
\b\d[\d,.]*\b
It will return 5000 and 99,999.99998713 - matching your requirements.
new
Operatornew
keywords also executes the constructor functionfunction Car() {
console.log(this) // this points to myCar
this.name = "Honda";
}
var myCar = new Car()
console.log(myCar) // Car {name: "Honda", constructor: Object}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // true
console.log(myCar.constructor) // function Car() {}
console.log(myCar.constructor === Car) // true
console.log(typeof myCar) // object
Object.create
to create a new objectObject.create
is used to create an object from another objectconst Car = {
name: "Honda"
}
var myCar = Object.create(Car)
console.log(myCar) // Object {}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // ERROR
console.log(myCar.constructor) // Anonymous function object
console.log(myCar.constructor === Car) // false
console.log(typeof myCar) // object
I had the same issue when working in a solution with multiple projects that share code. Turned out that I forgot to update the DLL in the folder of the 2nd project.
My suggestion is to take a good look at the 'project' column in the Error list window and make sure that project also uses the right DLL.
Make sure you run this first:
Class.forName("com.mysql.jdbc.Driver");
This forces the driver to register itself, so that Java knows how to handle those database connection strings.
For more information, see the MySQL Connector reference.
This worked for me:
// Check if URL contains the word "car" or "CAR"
if (stripos($_SERVER['REQUEST_URI'], 'car' )!==false){
echo "Car here";
} else {
echo "No car here";
}
If you want to use HTML in the echo, be sure to use ' ' instead of " ". I use this code to show an alert on my webpage https://geaskb.nl/ where the URL contains the word "Omnik" but hide the alert on pages that do not contain the word "Omnik" in the URL.
Explanation stripos : https://www.php.net/manual/en/function.stripos
If you are still not getting device token, try putting following code so to register your device for push notification.
It will also work on ios8 or more.
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
Borders of different colors. I used 3 items.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorAccent" />
</shape>
</item>
<item android:top="3dp">
<shape android:shape="rectangle">
<solid android:color="@color/light_grey" />
</shape>
</item>
<item
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="3dp">
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
</shape>
</item>
</layer-list>
Here is simple example of taking input from user on console based application: You can use readLine(). Take input from console for first number then press enter. After that take input for second number as shown in the image below:
func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
return firstNo + secondNo
}
let num1 = readLine()
let num2 = readLine()
var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)
let sum = solveMefirst(IntNum1!, secondNo: IntNum2!)
print(sum)
you are having the FindOpenSSL.cmake file in the cmake module(path usr/shared.cmake-3.5/modules) # Search OpenSSL
find_package(OpenSSL REQUIRED)
if( OpenSSL_FOUND )
include_directories(${OPENSSL_INCLUDE_DIRS})
link_directories(${OPENSSL_LIBRARIES})
message(STATUS "Using OpenSSL ${OPENSSL_VERSION}")
target_link_libraries(project_name /path/of/libssl.so /path/of/libcrypto.so)
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
Having included a dependency on spring-boot-configuration-processor
in build.gradle
:
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:2.4.1"
the only thing that worked for me, besides invalidating caches of IntelliJ and restarting, is
Reload All Gradle Projects
Clean
Build
Check out MSDN...
CREATE SCHEMA
: http://msdn.microsoft.com/en-us/library/ms189462.aspx
Then
ALTER SCHEMA
: http://msdn.microsoft.com/en-us/library/ms173423.aspx
Or you can check it on on SO...
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
I've been trying to get an image to be centered vertically and horizontally within a circle shape using hmtl and css.
After combining several points from this thread, here's what I came up with: jsFiddle
Here's another example of this within a three column layout: jsFiddle
CSS:
#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}
.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
HTML:
<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</div>
yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
and make sure there is no parent tags with position: relative in it
Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.
Demo:
my_tuple = (10, 20, 30, 40, 50)
# converting the tuple to the list
my_list = list(my_tuple)
print my_list # output: [10, 20, 30, 40, 50]
# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position
# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]
# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)
print my_tuple # output: (10, 30, 40)
Thanks
I found this solution for my project
I just set the minimum SDK version to 21 and that solves my problem
android {
defaultConfig {
...
minSdkVersion 21 //set the minimum sdk version 21
targetSdkVersion 29
}
...
}
if your minSdkVersion is 21 or higher multidex is enabled by default, and you do not need the multidex support library. To read more about multidex https://developer.android.com/studio/build/multidex.html
If you download the jquery easing plugin (check it out),then you just have to add this to your main.js file:
$('a.smooth-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top + 20
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
and also dont forget to add the smooth-scroll class to your a tags like this:
<li><a href="#about" class="smooth-scroll">About Us</a></li>
Here are TypeScript equivalents of some common .NET delegates:
interface Action<T>
{
(item: T): void;
}
interface Func<T,TResult>
{
(item: T): TResult;
}
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
I found out, that the problem occures on relative transforms in any way. translateX(50%), scale(1.1) or what ever. providing absolute values always works (does not produce blurry text(ures)).
None of the solutions mentions here worked, and I think there is not solution, yet (using Chrome 62.0.3202.94 while I am writing this).
In my case transform: translateY(-50%) translateX(-50%)
causes the blur (I want to center a dialog).
To reach a bit more "absolute" values, I had to set decimal values to transform: translateY(-50.09%) translateX(-50.09%)
.
NOTE
I am quite sure, that this values vary on different screen sizes. I just wanted to share my experiences, in case it helps someone.
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
And add below permission into your Androidmanifest.xml
file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me know if there is any issue.
the best and easiest way is to use "MySQL for Excel" app that is a free app from oracle. this app added a plugin to excel to export and import data to mysql. you can download that from here
Contents of table cell, variable height, could be more than 60px;
<div style="position: absolute; bottom: 0px;">
Notice
</div>
After reviewing the other answers and considering CodeInChaos' comments, along with CodeInChaos still biased (although less) answer, I thought a final ultimate cut and paste solution was needed. So while updating my answer I decided to go all out.
For an up to date version of this code, please visit the new Hg repository on Bitbucket: https://bitbucket.org/merarischroeder/secureswiftrandom. I recommend you copy and paste the code from: https://bitbucket.org/merarischroeder/secureswiftrandom/src/6c14b874f34a3f6576b0213379ecdf0ffc7496ea/Code/Alivate.SolidSwiftRandom/SolidSwiftRandom.cs?at=default&fileviewer=file-view-default (make sure you click the Raw button to make it easier to copy and make sure you have the latest version, I think this link goes to a specific version of the code, not the latest).
Updated notes:
End solution to question:
static char[] charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
public string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
char[] rName = new char[Length];
SecureFastRandom.GetNextBytesMax(rBytes, biasZone);
for (var i = 0; i < Length; i++)
{
rName[i] = charSet[rBytes[i] % charSet.Length];
}
return new string(rName);
}
But you need my new (untested) class:
/// <summary>
/// My benchmarking showed that for RNGCryptoServiceProvider:
/// 1. There is negligable benefit of sharing RNGCryptoServiceProvider object reference
/// 2. Initial GetBytes takes 2ms, and an initial read of 1MB takes 3ms (starting to rise, but still negligable)
/// 2. Cached is ~1000x faster for single byte at a time - taking 9ms over 1MB vs 989ms for uncached
/// </summary>
class SecureFastRandom
{
static byte[] byteCache = new byte[1000000]; //My benchmark showed that an initial read takes 2ms, and an initial read of this size takes 3ms (starting to raise)
static int lastPosition = 0;
static int remaining = 0;
/// <summary>
/// Static direct uncached access to the RNGCryptoServiceProvider GetBytes function
/// </summary>
/// <param name="buffer"></param>
public static void DirectGetBytes(byte[] buffer)
{
using (var r = new RNGCryptoServiceProvider())
{
r.GetBytes(buffer);
}
}
/// <summary>
/// Main expected method to be called by user. Underlying random data is cached from RNGCryptoServiceProvider for best performance
/// </summary>
/// <param name="buffer"></param>
public static void GetBytes(byte[] buffer)
{
if (buffer.Length > byteCache.Length)
{
DirectGetBytes(buffer);
return;
}
lock (byteCache)
{
if (buffer.Length > remaining)
{
DirectGetBytes(byteCache);
lastPosition = 0;
remaining = byteCache.Length;
}
Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
lastPosition += buffer.Length;
remaining -= buffer.Length;
}
}
/// <summary>
/// Return a single byte from the cache of random data.
/// </summary>
/// <returns></returns>
public static byte GetByte()
{
lock (byteCache)
{
return UnsafeGetByte();
}
}
/// <summary>
/// Shared with public GetByte and GetBytesWithMax, and not locked to reduce lock/unlocking in loops. Must be called within lock of byteCache.
/// </summary>
/// <returns></returns>
static byte UnsafeGetByte()
{
if (1 > remaining)
{
DirectGetBytes(byteCache);
lastPosition = 0;
remaining = byteCache.Length;
}
lastPosition++;
remaining--;
return byteCache[lastPosition - 1];
}
/// <summary>
/// Rejects bytes which are equal to or greater than max. This is useful for ensuring there is no bias when you are modulating with a non power of 2 number.
/// </summary>
/// <param name="buffer"></param>
/// <param name="max"></param>
public static void GetBytesWithMax(byte[] buffer, byte max)
{
if (buffer.Length > byteCache.Length / 2) //No point caching for larger sizes
{
DirectGetBytes(buffer);
lock (byteCache)
{
UnsafeCheckBytesMax(buffer, max);
}
}
else
{
lock (byteCache)
{
if (buffer.Length > remaining) //Recache if not enough remaining, discarding remaining - too much work to join two blocks
DirectGetBytes(byteCache);
Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
lastPosition += buffer.Length;
remaining -= buffer.Length;
UnsafeCheckBytesMax(buffer, max);
}
}
}
/// <summary>
/// Checks buffer for bytes equal and above max. Must be called within lock of byteCache.
/// </summary>
/// <param name="buffer"></param>
/// <param name="max"></param>
static void UnsafeCheckBytesMax(byte[] buffer, byte max)
{
for (int i = 0; i < buffer.Length; i++)
{
while (buffer[i] >= max)
buffer[i] = UnsafeGetByte(); //Replace all bytes which are equal or above max
}
}
}
For history - my older solution for this answer, used Random object:
private static char[] charSet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static rGen = new Random(); //Must share, because the clock seed only has Ticks (~10ms) resolution, yet lock has only 20-50ns delay.
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
static bool SlightlyMoreSecurityNeeded = true; //Configuration - needs to be true, if more security is desired and if charSet.Length is not divisible by 2^X.
public string GenerateRandomString(int Length) //Configurable output string length
{
byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
char[] rName = new char[Length];
lock (rGen) //~20-50ns
{
rGen.NextBytes(rBytes);
for (int i = 0; i < Length; i++)
{
while (SlightlyMoreSecurityNeeded && rBytes[i] >= biasZone) //Secure against 1/5 increased bias of index[0-7] values against others. Note: Must exclude where it == biasZone (that is >=), otherwise there's still a bias on index 0.
rBytes[i] = rGen.NextByte();
rName[i] = charSet[rBytes[i] % charSet.Length];
}
}
return new string(rName);
}
Performance:
Also check out:
These links are another approach. Buffering could be added to this new code base, but most important was exploring different approaches to removing bias, and benchmarking the speeds and pros/cons.
You're close. Just add the row to the tbody
instead of table
:
myTbody.insertRow();
Just get a reference to tBody
(myTbody
) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted
Here is one to sort various columns in a csv file by numeric and dictionary order, columns 5 and after as dictionary order
~/test>sort -t, -k1,1n -k2,2n -k3,3d -k4,4n -k5d sort.csv
1,10,b,22,Ga
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C
~/test>cat sort.csv
2,3,a,9,C
2,2,b,20,F
2,2,c,19,Gb,hj
2,2,c,19,Gb,hi
2,2,c,19,Ga
2,2,b,22,Ga
1,10,b,22,Ga
Note the -k1,1n means numeric starting at column 1 and ending at column 1. If I had done below, it would have concatenated column 1 and 2 making 1,10 sorted as 110
~/test>sort -t, -k1,2n -k3,3 -k4,4n -k5d sort.csv
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C
1,10,b,22,Ga
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:
public static class Extensions
{
public static string HtmlEncode(this string s)
{
return HttpUtility.HtmlEncode(s);
}
}
You can then do neat stuff like this:
string encoded = "<div>I need encoding</div>".HtmlEncode();
Steps to follow:
Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.
Insert a new module. From the menu: Insert -> Module (Don't skip this!).
Create a Public
function. Example:
Public Function findArea(ByVal width as Double, _
ByVal height as Double) As Double
' Return the area
findArea = width * height
End Function
Then use it in any cell like you would any other function: =findArea(B12,C12)
.
This is a a sensible point.
A null date is not a zero date. They may look the same, but they ain't. In mysql, a null date value is null. A zero date value is an empty string ('') and '0000-00-00 00:00:00'
On a null date "... where mydate = ''" will fail.
On an empty/zero date "... where mydate is null" will fail.
But now let's get funky. In mysql dates, empty/zero date are strictly the same.
by example
select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = ''; select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = '0000-00-00 00:00:00'
will BOTH output: '0000-00-00 00:00:00'. if you update myDate with '' or '0000-00-00 00:00:00', both selects will still work the same.
In php, the mysql null dates type will be respected with the standard mysql connector, and be real nulls ($var === null, is_null($var)). Empty dates will always be represented as '0000-00-00 00:00:00'.
I strongly advise to use only null dates, OR only empty dates if you can. (some systems will use "virual" zero dates which are valid Gregorian dates, like 1970-01-01 (linux) or 0001-01-01 (oracle).
empty dates are easier in php/mysql. You don't have the "where field is null" to handle. However, you have to "manually" transform the '0000-00-00 00:00:00' date in '' to display empty fields. (to store or search you don't have special case to handle for zero dates, which is nice).
Null dates need better care. you have to be careful when you insert or update to NOT add quotes around null, else a zero date will be inserted instead of null, which causes your standard data havoc. In search forms, you will need to handle cases like "and mydate is not null", and so on.
Null dates are usually more work. but they much MUCH MUCH faster than zero dates for queries.
It is not possible directly. You may as well write some preprocessor which can handle that.
If I understand it correctly then below are the things that can be helpful to achieve that:
Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)
If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.
Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.
JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".
Hope it helps.
There are two ways to achieve that:
-rpath
linker option:gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib
Use LD_LIBRARY_PATH
environment variable - put this line in your ~/.bashrc
file:
export LD_LIBRARY_PATH=/home/user/.usr/lib
This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.
For a quick test, you can also do (in bash at least):
LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out
which has the advantage of not changing your library path for everything else.
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
For windows system you should be able to run php by following below steps:
$ php -S localhost:8000
command in a folder which you want to serve the pages from.I had the same problem (I'm running cygwin)
Starting a shell through cygwin.bat didn't help, but starting a shell through MingWShell did. Not quite sure why, but I think it had something to do with the extra layer that cygwin puts between the executing script and the underlying filesystem.
I was running pip install from within a virtual env's cygwin to install django sentry..
You can use new stdClass()
(which is recommended):
$obj_a = new stdClass();
$obj_a->name = "John";
print_r($obj_a);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
$obj_b = (object) [];
$obj_b->name = "John";
print_r($obj_b);
// outputs:
// stdClass Object ( [name] => John )
Or you can convert the null
value to an object which produces a new empty instance of the stdClass built-in class:
$obj_c = (object) null;
$obj_c->name = "John";
print($obj_c);
// outputs:
// stdClass Object ( [name] => John )
auto
is not a valid value for padding
property, the only thing you can do is take out padding: 0;
from the *
declaration, else simply assign padding
to respective property block.
If you remove padding: 0;
from * {}
than browser will apply default styles to your elements which will give you unexpected cross browser positioning offsets by few pixels, so it is better to assign padding: 0;
using *
and than if you want to override the padding, simply use another rule like
.container p {
padding: 5px;
}
You could create a random number using FLOOR(RAND() * n) as randnum
(n is an integer), however if you do not need the same random number to be repeated then you will have to somewhat store in a temp table. So you can check it against with where randnum not in (select * from temptable)
...
$sub_total_price = 0;
foreach($booking_list as $key=>$value) {
$sub_total_price += ($price * $quantity);
}
echo $sub_total_price;
it's working 100% :)
Enhanced diff command with color, side by side and alias
Let's say the file contents are like:
cat /tmp/test1.txt
1
2
3
4
5
8
9
and
cat /tmp/test2.txt
1
1.5
2
4
5
6
7
Now comparing side-by-side
diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always /tmp/test1.txt /tmp/test2.txt
> 1.5
3 <
8 | 6
9 | 7
You can define alias to use
alias diff='diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always'
Then new diff result:
diff /tmp/test1.txt /tmp/test2.txt
> 1.5
3 <
8 | 6
9 | 7
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
There is a super() in python also.
Example for how a super class method is called from a sub class method
class Dog(object):
name = ''
moves = []
def __init__(self, name):
self.name = name
def moves_setup(self,x):
self.moves.append('walk')
self.moves.append('run')
self.moves.append(x)
def get_moves(self):
return self.moves
class Superdog(Dog):
#Let's try to append new fly ability to our Superdog
def moves_setup(self):
#Set default moves by calling method of parent class
super().moves_setup("hello world")
self.moves.append('fly')
dog = Superdog('Freddy')
print (dog.name)
dog.moves_setup()
print (dog.get_moves())
This example is similar to the one explained above.However there is one difference that super doesn't have any arguments passed to it.This above code is executable in python 3.4 version.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.
E.g.,
ml = [[0], [1]] * 10
After,
random.shuffle(ml)
The number of [0] may be 9 or 8, but not exactly 10.
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
Try This
var data = 'allow~5';
var result=data.split('~');
RESULT
alert(result[0]);
I have just found a really good example of how to do this here: http://developer.android.com/reference/android/webkit/WebView.html . You just need to change the setprogress from:
activity.setProgress(progress * 1000);
to
activity.setProgress(progress * 100);
I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.
public static class DateTimeWithZone
{
private static readonly TimeZoneInfo timeZone;
static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}
public static DateTime LocalTime(this DateTime t)
{
return TimeZoneInfo.ConvertTime(t, timeZone);
}
}
Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.
I believe this example would do the trick:
//book[descendant::title[@lang='it']]
This allows you to select all book
elements that contain a child title
element (regardless of how deep it is nested) containing language attribute value equal to 'it'.
I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.
A very detailed explanation about copying, passing and comparing by value and by reference is in this chapter of the "JavaScript: The Definitive Guide" book.
Before we leave the topic of manipulating objects and arrays by reference, we need to clear up a point of nomenclature.
The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book.
Here, we mean simply that a reference to an object or array -- not the object itself -- is passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside of the function.
Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
You need to go here https://security.google.com/settings/security/apppasswords
then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.
public boolean hasLoop(Node start){
TreeSet<Node> set = new TreeSet<Node>();
Node lookingAt = start;
while (lookingAt.peek() != null){
lookingAt = lookingAt.next;
if (set.contains(lookingAt){
return false;
} else {
set.put(lookingAt);
}
return true;
}
// Inside our Node class:
public Node peek(){
return this.next;
}
Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?
I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.
My solution for BlueJ is to edit the New Class template "stdclass.tmpl" in Program Files (x86)\BlueJ\lib\english\templates\newclass and add this method:
public static <T> void p(T s)
{
System.out.println(s);
}
Or this other version:
public static void p(Object s)
{
System.out.println(s);
}
As for Eclipse I'm using the suggested shortcut syso + <Ctrl> + <Space>
:)
can use this,
lemons ? alert("please give me a lemonade") : alert("then give me a beer");
explanation: if lemons
is true then alert("please give me a lemonade")
, if not, alert("then give me a beer")
Below is an example where we can convert float value without any scientific notation.
DECLARE @Floater AS FLOAT = 100000003.141592653
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 10
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 100
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SELECT LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
,FORMAT(@Floater, '')
In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.
try FileSaver.js
library. it might help.
Regular expression works too:
import re
with open("depression.txt") as f:
l = re.split(' ', re.sub('\n',' ', f.read()))[:-1]
print (l)
['I', 'feel', 'empty', 'and', 'dead', 'inside']
Just use JavaScript. Then compatible with most and older browsers. Use the escape sequence \n for newline.
document.getElementById("ElementID").title = 'First Line text \n Second line text'
You're looking for the /Y
switch.
Very simple, you create an array containing zeros using the reference shape:
result = np.zeros(b.shape)
# actually you can also use result = np.zeros_like(b)
# but that also copies the dtype not only the shape
and then insert the array where you need it:
result[:a.shape[0],:a.shape[1]] = a
and voila you have padded it:
print(result)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
You can also make it a bit more general if you define where your upper left element should be inserted
result = np.zeros_like(b)
x_offset = 1 # 0 would be what you wanted
y_offset = 1 # 0 in your case
result[x_offset:a.shape[0]+x_offset,y_offset:a.shape[1]+y_offset] = a
result
array([[ 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 1., 1.]])
but then be careful that you don't have offsets bigger than allowed. For x_offset = 2
for example this will fail.
If you have an arbitary number of dimensions you can define a list of slices to insert the original array. I've found it interesting to play around a bit and created a padding function that can pad (with offset) an arbitary shaped array as long as the array and reference have the same number of dimensions and the offsets are not too big.
def pad(array, reference, offsets):
"""
array: Array to be padded
reference: Reference array with the desired shape
offsets: list of offsets (number of elements must be equal to the dimension of the array)
"""
# Create an array of zeros with the reference shape
result = np.zeros(reference.shape)
# Create a list of slices from offset to offset + shape in each dimension
insertHere = [slice(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]
# Insert the array in the result at the specified offsets
result[insertHere] = a
return result
And some test cases:
import numpy as np
# 1 Dimension
a = np.ones(2)
b = np.ones(5)
offset = [3]
pad(a, b, offset)
# 3 Dimensions
a = np.ones((3,3,3))
b = np.ones((5,4,3))
offset = [1,0,0]
pad(a, b, offset)
You can do this:
//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));
//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
if(linkList.get(i).getAttribute("href").contains("long"))
{
linkList.get(i).click();
break;
}
}
in this what we r doing is first we are finding all the <a>
tags and storing them in a list.After
that we are iterating the list one by one to find <a>
tag whose href attribute contains long string. And then we click on that particular <a>
tag and comes out of the loop.
Click "view details" to find the inner exception.
Assuming all of these columns are int
, then the first thing to sort out is converting one or more of them to a better data type - int
division performs truncation, so anything less than 100% would give you a result of 0:
select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)
from
CSPGI09_OVERSHIPMENT
Here, I've mutiplied one of the numbers by 100.0
which will force the result of the calculation to be done with float
s rather than int
s. By choosing 100
, I'm also getting it ready to be treated as a %
.
I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (-
and /
) at the same level, and so were relying on the precedence rules to define which operator applied first.
You can use the autocorrect lib to spell check in python.
Example Usage:
from autocorrect import Speller
spell = Speller(lang='en')
print(spell('caaaar'))
print(spell('mussage'))
print(spell('survice'))
print(spell('hte'))
Result:
caesar
message
service
the
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)
$.extend({_x000D_
confirm: function(message, title, okAction) {_x000D_
$("<div></div>").dialog({_x000D_
// Remove the closing 'X' from the dialog_x000D_
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },_x000D_
width: 500,_x000D_
buttons: [{_x000D_
text: localizationInstance.translate("Ok"),_x000D_
click: function () {_x000D_
$(this).dialog("close");_x000D_
okAction();_x000D_
}_x000D_
},_x000D_
{_x000D_
text: localizationInstance.translate("Cancel"),_x000D_
click: function() {_x000D_
$(this).dialog("close");_x000D_
}_x000D_
}],_x000D_
close: function(event, ui) { $(this).remove(); },_x000D_
resizable: false,_x000D_
title: title,_x000D_
modal: true_x000D_
}).text(message);_x000D_
}_x000D_
});
_x000D_
With the Continuous Formatting extension (commercial, developed by me), the code is formatted really automatically as you type.
The question is a little tricky to understand but I'm guessing that the problem is that you're trying to remove elements from the Dictionary while you iterate over the keys. I think in that case you have no choice but to use a second array.
ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
if (<your condition here>)
{
lDict.Remove(lKey);
}
}
If you can use generic lists and dictionaries instead of an ArrayList then I would, however the above should just work.
You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:
pip install pypiwin32
Currently I think this is "the easiest" way to get in working :) Hope this helps.
I'm not sure if this is a good solution but it removed the error. I commented out the line:
from numpy._distributor_init import NUMPY_MKL
and it worked. Not sure if this will cause other features to break though
Now that the new anaconda individual edition 2020 distribution is out, the procedure that follows is working:
Update conda in your base env:
conda update conda
Create a new environment for Python 3.8, specifying anaconda for the full distribution specification, not just the minimal environment:
conda create -n py38 python=3.8 anaconda
Activate the new environment:
conda activate py38
python --version
Python 3.8.1
Number of packages installed: 303
Or you can do:
conda create -n py38 anaconda=2020.02 python=3.8
--> UPDATE: Finally, Anaconda3-2020.07 is out with core Python 3.8.3
You can download Anaconda with Python 3.8 from https://www.anaconda.com/products/individual
Structs can have functions just like classes. The only difference is that they are public by default:
struct A {
void f() {}
};
Additionally, structs can also have constructors and destructors.
struct A {
A() : x(5) {}
~A() {}
private: int x;
};
Below code will only print files within directory and exclude directories within given directory while traversing.
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char path[1000]="/home/joy/Downloads";
d = opendir(path);
char full_path[1000];
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//Condition to check regular file.
if(dir->d_type==DT_REG){
full_path[0]='\0';
strcat(full_path,path);
strcat(full_path,"/");
strcat(full_path,dir->d_name);
printf("%s\n",full_path);
}
}
closedir(d);
}
return(0);
}
Extensions are not supported, see: https://developers.google.com/chrome/mobile/docs/faq .
Specifically:
Does Chrome for Android now support the embedded WebView for a hybrid native/web app?
A Chrome-based WebView is included in Android 4.4 (KitKat) and later. See the WebView overview for details.
Does Chrome for Android support apps and extensions?
Chrome apps and extensions are currently not supported on Chrome for Android. We have no plans to announce at this time.
Can I write and deploy web apps on Chrome for Android?
Though Chrome apps are not currently supported, we would love to see great interactive web sites accessible by URL.
If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set
public class Pair<First, Second> {
private First first;
private Second second;
public Pair(First first, Second second) {
this.first = first;
this.second = second;
}
public void setFirst(First first) {
this.first = first;
}
public void setSecond(Second second) {
this.second = second;
}
public First getFirst() {
return first;
}
public Second getSecond() {
return second;
}
public void set(First first, Second second) {
setFirst(first);
setSecond(second);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
if (second != null ? !second.equals(pair.second) : pair.second != null) return false;
return true;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
}
I ended up here looking for a HSV color picker that offered transparency and copy/paste of the hex value. None of the existing answers met those needs, so here's the library I ended up writing:
HSV-Alpha Color Picker for Android (GitHub).
HSV-Alpha Color Picker Demo (Google Play).
I hope it's useful for somebody else.
If anyone is interested in a sortable list with a changing index per listitem (1st, 2nd, 3th etc...:
http://jsfiddle.net/aph0c1rL/1/
$(".sortable").sortable(
{
handle: '.handle'
, placeholder: 'sort-placeholder'
, forcePlaceholderSize: true
, start: function( e, ui )
{
ui.item.data( 'start-pos', ui.item.index()+1 );
}
, change: function( e, ui )
{
var seq
, startPos = ui.item.data( 'start-pos' )
, $index
, correction
;
// if startPos < placeholder pos, we go from top to bottom
// else startPos > placeholder pos, we go from bottom to top and we need to correct the index with +1
//
correction = startPos <= ui.placeholder.index() ? 0 : 1;
ui.item.parent().find( 'li.prize').each( function( idx, el )
{
var $this = $( el )
, $index = $this.index()
;
// correction 0 means moving top to bottom, correction 1 means bottom to top
//
if ( ( $index+1 >= startPos && correction === 0) || ($index+1 <= startPos && correction === 1 ) )
{
$index = $index + correction;
$this.find( '.ordinal-position').text( $index + ordinalSuffix( $index ) );
}
});
// handle dragged item separatelly
seq = ui.item.parent().find( 'li.sort-placeholder').index() + correction;
ui.item.find( '.ordinal-position' ).text( seq + ordinalSuffix( seq ) );
} );
// this function adds the correct ordinal suffix to the provide number
function ordinalSuffix( number )
{
var suffix = '';
if ( number / 10 % 10 === 1 )
{
suffix = "th";
}
else if ( number > 0 )
{
switch( number % 10 )
{
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
}
return suffix;
}
Your markup can look like this:
<ul class="sortable ">
<li >
<div>
<span class="ordinal-position">1st</span>
A header
</div>
<div>
<span class="icon-button handle"><i class="fa fa-arrows"></i></span>
</div>
<div class="bpdy" >
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</div>
</li>
<li >
<div>
<span class="ordinal-position">2nd</span>
A header
</div>
<div>
<span class="icon-button handle"><i class="fa fa-arrows"></i></span>
</div>
<div class="bpdy" >
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</div>
</li>
etc....
</ul>
You have enabled CORS and enabled Access-Control-Allow-Origin : *
in the server.If still you get GET
method working and POST
method is not working then it might be because of the problem of Content-Type
and data
problem.
First AngularJS transmits data using Content-Type: application/json
which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded
Example :-
$scope.formLoginPost = function () {
$http({
url: url,
method: "POST",
data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Note : I am using $.params
to serialize the data to use Content-Type: x-www-form-urlencoded
. Alternatively you can use the following javascript function
function params(obj){
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
and use params({ 'username': $scope.username, 'Password': $scope.Password })
to serialize it as the Content-Type: x-www-form-urlencoded
requests only gets the POST data in username=john&Password=12345
form.
In npm 6.x you can use
npm i --package-lock-only
According to https://docs.npmjs.com/cli/install.html
The --package-lock-only argument will only update the package-lock.json, instead of checking node_modules and downloading dependencies.
Call
perror("execl");
in case of error.
Sample:
if(read(fd, buf, 1)==-1) {
perror("read");
}
The manpages of errno(3)
and perror(3)
are interesting, too...
The short answer: there is no difference.
The long answer: CHARACTER VARYING
is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR
is a shorter alias which all modern databases also support. I prefer VARCHAR
because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump
and \d
will output character varying
.
Also, you are probably inside the .git subfolder, move up one folder to your project root.
CharSequence
is a contract (interface), and String
is an implementation of this contract.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The documentation for CharSequence
is:
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
If you just want to verify you don't have random garbage in the field (i.e., from form spammers) this regex should do nicely:
^[0-9+\(\)#\.\s\/ext-]+$
Note that it doesn't have any special rules for how many digits, or what numbers are valid in those digits, it just verifies that only digits, parenthesis, dashes, plus, space, pound, asterisk, period, comma, or the letters e
, x
, t
are present.
It should be compatible with international numbers and localization formats. Do you foresee any need to allow square, curly, or angled brackets for some regions? (currently they aren't included).
If you want to maintain per digit rules (such as in US Area Codes and Prefixes (exchange codes) must fall in the range of 200-999) well, good luck to you. Maintaining a complex rule-set which could be outdated at any point in the future by any country in the world does not sound fun.
And while stripping all/most non-numeric characters may work well on the server side (especially if you are planning on passing these values to a dialer), you may not want to thrash the user's input during validation, particularly if you want them to make corrections in another field.
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
string management is an expensive process. keeping strings immutable allows repeated strings to be reused, rather than re-created.
Just thought i would share a solution also based on this that works with the Knowntype attribute using reflection , had to get derived class from any base class, solution can benefit from recursion to find the best matching class though i didn't need it in my case, matching is done by the type given to the converter if it has KnownTypes it will scan them all until it matches a type that has all the properties inside the json string, first one to match will be chosen.
usage is as simple as:
string json = "{ Name:\"Something\", LastName:\"Otherthing\" }";
var ret = JsonConvert.DeserializeObject<A>(json, new KnownTypeConverter());
in the above case ret will be of type B.
JSON classes:
[KnownType(typeof(B))]
public class A
{
public string Name { get; set; }
}
public class B : A
{
public string LastName { get; set; }
}
Converter code:
/// <summary>
/// Use KnownType Attribute to match a divierd class based on the class given to the serilaizer
/// Selected class will be the first class to match all properties in the json object.
/// </summary>
public class KnownTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return System.Attribute.GetCustomAttributes(objectType).Any(v => v is KnownTypeAttribute);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(objectType); // Reflection.
// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is KnownTypeAttribute)
{
KnownTypeAttribute k = (KnownTypeAttribute) attr;
var props = k.Type.GetProperties();
bool found = true;
foreach (var f in jObject)
{
if (!props.Any(z => z.Name == f.Key))
{
found = false;
break;
}
}
if (found)
{
var target = Activator.CreateInstance(k.Type);
serializer.Populate(jObject.CreateReader(),target);
return target;
}
}
}
throw new ObjectNotFoundException();
// Populate the object properties
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document
it will return null
. null is a Falsy and can be used as boolean expression
in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
You need to declare out
as a byte array with a length equal to the lengths of ciphertext
and mac
added together, and then copy ciphertext
over the beginning of out
and mac
over the end, using arraycopy.
byte[] concatenateByteArrays(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
Well, I have actually found the problem.
The most people who try to make a connection using socket.Connect();
get an exception called Java.IO.IOException: read failed, socket might closed, read ret: -1
.
In some cases it also depends on your Bluetooth device, because there are two different types of Bluetooth, namely BLE (low energy) and Classic.
If you want to check the type of your Bluetooth device is, here's the code:
String checkType;
var listDevices = BluetoothAdapter.BondedDevices;
if (listDevices.Count > 0)
{
foreach (var btDevice in listDevices)
{
if(btDevice.Name == "MOCUTE-032_B52-CA7E")
{
checkType = btDevice.Type.ToString();
Console.WriteLine(checkType);
}
}
}
I've been trying for days to solve the problem, but since today I have found the problem. The solution from @matthes has unfortunately still a few issues as he said already, but here's my solution.
At the moment I work in Xamarin Android, but this should also work for other platforms.
SOLUTION
If there is more than one paired device, then you should remove the other paired devices. So keep only the one that you want to connect (see the right image).
In the left image you see that I have two paired devices, namely "MOCUTE-032_B52-CA7E" and "Blue Easy". That's the issue, but I have no idea why that problem occurs. Maybe the Bluetooth protocol is trying to get some information from another Bluetooth device.
However, the socket.Connect();
works great right now, without any problems. So I just wanted to share this, because that error is really annoying.
Good luck!
assuming you have a SQL table called mydata - you can load data from a csv file as follows:
COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;
For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html
If you don't want all of your SQL statements to be echoed, but you only want to see the easily identifiable results of your script, do it this way:
set echo on
REM MyFirstTable
set echo off
delete from MyFirstTable;
set echo on
REM MySecondTable
set echo off
delete from MySecondTable;
The output from the above example will look something like this:
-REM MyFirstTable
13 rows deleted.
-REM MySecondTable
27 rows deleted.
I know that the question was for Java
. But I want to share a possible solution for Kotlin
because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray
into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray()
directly on a JSONArray
instance.
I use this javascript line to block the pop up asking for form resubmission on refresh once the form is submitted.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
Just place this line at the footer of your file and see the magic
tick_params is very useful for setting tick properties. Labels can be moved to the top with:
ax.tick_params(labelbottom=False,labeltop=True)
I saw a question the other day where someone inadvertently used an incomplete type by specifying something like
struct a {
int q;
};
struct A *x;
x->q = 3;
The compiler knew that struct A
was a struct, despite A
being totally undefined, by virtue of the struct
keyword.
That was in C++, where such usage of struct
is atypical (and, it turns out, can lead to foot-shooting). In C if you do
typedef struct a {
...
} a;
then you can use a
as the typename and omit the struct
later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.
I just changed @Jotne's answer for "for loop".
for i in `seq 11 20`; do host myserver-$i | awk -v i="$i" '{print "myserver-"i" " $4}'; done
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.
SQL Server 2019 Express Edition (English):
SQL Server 2017 Express Edition (English):
SQL Server 2016 with SP2 Express Edition (English):
SQL Server 2016 with SP1 Express Edition (English):
And here is how to use Fiddler.
template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;
the above helpers let you work with types as values.
class A {
template<class T>
A( tag<T> );
};
the tag<T>
type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:
auto a = A(tag<int>{});
You can pass in more than one type:
class A {
template<class T, class U, class V>
A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});
Implementing window.onbeforeprint and window.onafterprint
The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70
To approach this I'm using Adam's answer with a simple modification:
function print() {
(function () {
let afterPrintCounter = !!window.chrome ? 0 : 1;
let beforePrintCounter = !!window.chrome ? 0 : 1;
var beforePrint = function () {
beforePrintCounter++;
if (beforePrintCounter === 2) {
console.log('Functionality to run before printing.');
}
};
var afterPrint = function () {
afterPrintCounter++;
if (afterPrintCounter === 2) {
console.log('Functionality to run after printing.');
//window.close();
}
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
//window.print(); //To print the page when it is loaded
}
I'm calling it in here:
<body onload="print();">
This works for me. Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla). For detecting the browser you can refer to this answer
you can change the size of an icon using the font size rather than setting the height and width of an icon. Here is how you do it:
<i class="fa fa-minus-square-o" style="font-size: 0.73em;"></i>
There are 4 ways to specify the dimensions of the icon.
px : give fixed pixels to your icon
em : dimensions with respect to your current font. Say ur current font is 12px then 1.5em will be 18px (12px + 6px).
pt : stands for points. Mostly used in print media
% : percentage. Refers to the size of the icon based on its original size.
It works and there's even a common pattern for your approach: the Adapter pattern. But of course, (1) it does not work for casting java primitives to objects and (2) the class has to be adaptable (usually by implementing a custom interface).
With this pattern you could do something like:
Wolf bigBadWolf = new Wolf();
Sheep sheep = (Sheep) bigBadWolf.getAdapter(Sheep.class);
and the getAdapter method in Wolf class:
public Object getAdapter(Class clazz) {
if (clazz.equals(Sheep.class)) {
// return a Sheep implementation
return getWolfDressedAsSheep(this);
}
if (clazz.equals(String.class)) {
// return a String
return this.getName();
}
return null; // not adaptable
}
For you special idea - that is impossible. You can't use a String value for casting.
Since the general guideline in Python is to ask for forgiveness rather than permission, I think the most pythonic way to detect a string/scalar from a sequence is to check if it contains an integer:
try:
1 in a
print('{} is a sequence'.format(a))
except TypeError:
print('{} is a scalar or string'.format(a))
lines = f.readlines()
reads all the lines of the file f. So it makes sense that there aren't any more line to read in the file f. If you want to read the file line by line, use readline().
I had the same problem. I enabled vtx in bios and it didn't worked. After a doublecheck in the bios I recogniced that the bios said that you have to poweroff (and realy power off) the computer. After that it worked. Heavy Pitfall :)
I create a student
table with three column id, student,age
. show you this example
declare @id int
select @id = 1
while @id >=1 and @id <= 1000
begin
insert into student values(@id, 'jack' + convert(varchar(5), @id), 12)
select @id = @id + 1
end
this is the result about the example
While browsing around to figure out about the hash in the folder name, I came across (via this answer):
http://blogs.msdn.com/b/rprabhu/archive/2005/06/29/433979.aspx
(edit: Wayback Machine link: https://web.archive.org/web/20160307233557/http://blogs.msdn.com:80/b/rprabhu/archive/2005/06/29/433979.aspx)
The exact path of the
user.config
files looks something like this:
<Profile Directory>\<Company Name>\<App Name>_<Evidence Type>_<Evidence Hash>\<Version>\user.config
where
<Profile Directory>
- is either the roaming profile directory or the local one. Settings are stored by default in the localuser.config
file. To store a setting in the roaminguser.config
file, you need to mark the setting with theSettingsManageabilityAttribute
withSettingsManageability
set toRoaming
.
<Company Name>
- is typically the string specified by theAssemblyCompanyAttribute
(with the caveat that the string is escaped and truncated as necessary, and if not specified on the assembly, we have a fallback procedure).
<App Name>
- is typically the string specified by theAssemblyProductAttribute
(same caveats as for company name).
<Evidence Type>
and<Evidence Hash>
- information derived from the app domain evidence to provide proper app domain and assembly isolation.
<Version>
- typically the version specified in theAssemblyVersionAttribute
. This is required to isolate different versions of the app deployed side by side.The file name is always simply '
user.config
'.
@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO
to SET
to set the variables rather thon ECHOing them...
See for
documentation for a full list.
ceztko's test case (for reference)
@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
New C++0x standard. Please see section 8.4.3 in the N3242 working draft
I had a similar problem that I solved with the following technique:
The exception was thrown at the following line of code (see the text decorated with ** below):
static void Main(string[] args)
{
double number = 0;
string numberStr = string.Format("{0:C2}", 100);
**number = Double.Parse(numberStr);**
Console.WriteLine("The number is {0}", number);
}
After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:
number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number
At that point the Parse(...) method worked as expected.
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
The content of the table/tables in PostgreSQL database can be deleted in several ways.
Deleting table content using sql:
Deleting content of one table:
TRUNCATE table_name;
DELETE FROM table_name;
Deleting content of all named tables:
TRUNCATE table_a, table_b, …, table_z;
Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):
TRUNCATE table_a, table_b CASCADE;
Deleting table content using pgAdmin:
Deleting content of one table:
Right click on the table -> Truncate
Deleting content of table and tables that reference to it:
Right click on the table -> Truncate Cascaded
Difference between delete and truncate:
From the documentation:
DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html
TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html
Working with table that is referenced from other table:
When you have database that has more than one table the tables have probably relationship. As an example there are three tables:
create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);
create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
And some prepared data for these tables:
insert into customers values (1, 'John', 'Smith');
insert into orders values
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);
insert into loyalty_cards values (100, 'A123456789', 1);
Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)
TRUNCATE customers, loyalty_cards, orders;
or just the table that is referenced with CASCADE key word (you can name more tables than just one)
TRUNCATE customers CASCADE;
The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.
i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.
Go to the download page and download the Windows x86
version with filename jdk-7-windows-i586.exe
.
The best choice to me was to create a directive to do the work, because $location.hash()
and
$anchorScroll()
hijack the URL creating lots of problems to my SPA routing.
MyModule.directive('myAnchor', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attrs, ngModel) {
return elem.bind('click', function() {
//other stuff ...
var el;
el = document.getElementById(attrs['myAnchor']);
return el.scrollIntoView();
});
}
};
});
foreach(array_keys($array) as $key) {
// do stuff
}
You would have to turn your font into a web font as shown in these SO questions:
However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.
One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.
One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.
Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.
You can use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
But I don't know whether it should be considered more right than to use Calendar ...
It is considered bad practice to invoke the actual generator (e.g. via make
) if using CMake. It is highly recommended to do it like this:
Configure phase:
cmake -Hfoo -B_builds/foo/debug -G"Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_DEBUG_POSTFIX=d -DCMAKE_INSTALL_PREFIX=/usr
Build and Install phases
cmake --build _builds/foo/debug --config Debug --target install
When following this approach, the generator can be easily switched (e.g. -GNinja
for Ninja) without having to remember any generator-specific commands.
Turns out I have not looked good enough at my stack trace, the problem is not that the external JAR is not included.
The problem is that Android platform is missing javax.naming.* and many other packages that the external JAR has dependencies too.
Adding external JAR files, and setting Order and Export in Eclipse works as expected with Android projects.
Best cross browser solution (mostly for IE support) like @Steve said is to make a div 98px in width and height than add a border 1px around it, or you could make a background image for div 100x100 px and draw a border on it.
You probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals
function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr
function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
You can add more than 1 element in one shot to array using array_push,
e.g. array_push($array_name, $element1, $element2,...)
Where $element1, $element2,... are elements to be added to array.
But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.
An alternative crontab method inspired by this answer and this blog post.
1. Create a bash script file (change bob to desired user).
vi /home/bob/node_server_init.sh
2. Copy and paste this inside the file you've just created.
#!/bin/sh
export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null
Make sure to edit the paths above according to your config!
3. Make sure the bash script can be executed.
chmod 700 /home/bob/node_server_init.sh
4. Test the bash script.
sh /home/bob/node_server_init.sh
5. Replace "bob" with the runtime user for node.
crontab -u bob -e
6. Copy and paste (change bob to desired user).
@reboot /bin/sh /home/bob/node_server_init.sh
Save the crontab.
You've made it to the end, your prize is a reboot (to test) :)
Note that if you include android:id...
into the <include />
tag, it will override whatever id was defined inside the included layout. For example:
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_id_if_needed"
layout="@layout/yourlayout" />
yourlayout.xml:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/some_other_id">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
</LinearLayout>
Then you would reference this included layout in code as follows:
View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);
viewport
meta tag on mobile browser,
The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.
Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".
You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...
C:\>PowerShell -Command "temperature | prismcom.exe usb"
Please read up on Understanding the Windows PowerShell Pipeline
You can also type in C:\>PowerShell
at the command-line and it'll put you in PS C:\>
mode instanctly, where you can directly start writing PS.
printStackTrace
is a method of the Throwable
class. This method displays error message in the console; where we are getting the exception in the source code. These methods can be used with catch block and they describe:
The three methods which describe the exception on the console (in which printStackTrace is one of them) are:
printStackTrace()
toString()
getMessage()
Example:
public class BabluGope {
public static void main(String[] args) {
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
e.printStackTrace();
// System.err.println(e.toString());
//System.err.println(e.getMessage());
}
}
}
If you only need a current value and above options don't work, you can use it this way.
$('#input').on('change', () => {
const current = document.getElementById('input').value;
}
Take a look at LoadBooster(https://www.loadbooster.com). It utilizes headless scriptable browser PhantomJS/CasperJs to test web sites. Phantomjs will parse and render every page, execute the client-side script. The headless browser approach is easier to write test scenarios to support complex AJAX heavy Web 2.0 app,browser navigation, mouse click and keystrokes into the browser or wait until an element exists in DOM. LoadBooster support selenium HTML script too.
Disclaimer: I work for LoadBooster.
Add this:
$(document).ready(function(){
$(document).on('shown.bs.modal','.modal', function () {
// DO EVENTS
});
});
There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:
I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.
There is also str_sub
from the stringr package
x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
Try to keep your files closer to the file system root. More details : for technical reasons, Git for Windows cannot create files or directories when the absolute path is longer than 260 characters.
For a small number of variables, you can build the plot manually yourself:
ggplot(test_data, aes(date)) +
geom_line(aes(y = var0, colour = "var0")) +
geom_line(aes(y = var1, colour = "var1"))
Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.
*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.
I used this code to write directly to the event log Application:
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):
Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.
I use the command pkill
for this:
NAME
pgrep, pkill - look up or signal processes based on name and
other attributes
SYNOPSIS
pgrep [options] pattern
pkill [options] pattern
DESCRIPTION
pgrep looks through the currently running processes and lists
the process IDs which match the selection criteria to stdout.
All the criteria have to match. For example,
$ pgrep -u root sshd
will only list the processes called sshd AND owned by root.
On the other hand,
$ pgrep -u root,daemon
will list the processes owned by root OR daemon.
pkill will send the specified signal (by default SIGTERM)
to each process instead of listing them on stdout.
If your code runs via interpreter (java, python, ...) then the name of the process is the name of the interpreter. You need to user the argument --full. This matches against the command name and the arguments.
I ran into the same issue. Whenever I ran my test, it kept saying classes not found in the classpath. I tried to fix the testng.xml file, clean up the project and pretty much everything the answers say here, but none worked. Finally I checked my referenced libraries in build path and there were 34 invalid libraries, turns out I had renamed one of the folders from the path that I had taken the jar files from. I fixed the path and the test ran successfully.
So it might be fruitful to check if there are any errors in the referenced jar files before trying the other methods to fix this issue.
Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.
For reference you can read http://it.php.net/manual/en/book.dom.php
Now we will take a quick tour of the code below.
These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.
<?php
/* create a dom document with encoding utf8 */
$domtree = new DOMDocument('1.0', 'UTF-8');
/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("xml");
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentTrack = $domtree->createElement("track");
$currentTrack = $xmlRoot->appendChild($currentTrack);
/* you should enclose the following two lines in a cicle */
$currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
$currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));
$currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
$currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));
/* get the xml printed */
echo $domtree->saveXML();
?>
Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
I had a situation where I could not use any of the above answers. My case involved working with search page where users would get "confirm form resubmission" if the clicked back after navigating to any of the search results. I wrote the following javascript which worked around the issue. It isn't a great fix as it is a bit blinky, and it doesn't work on IE8 or earlier. Still, though this might be useful or interesting for someone dealing with this issue.
jQuery(document).ready(function () {
//feature test
if (!history)
return;
var searchBox = jQuery("#searchfield");
//This occurs when the user get here using the back button
if (history.state && history.state.searchTerm != null && history.state.searchTerm != "" && history.state.loaded != null && history.state.loaded == 0) {
searchBox.val(history.state.searchTerm);
//don't chain reloads
history.replaceState({ searchTerm: history.state.searchTerm, page: history.state.page, loaded: 1 }, "", document.URL);
//perform POST
document.getElementById("myForm").submit();
return;
}
//This occurs the first time the user hits this page.
history.replaceState({ searchTerm: searchBox.val(), page: pageNumber, loaded: 0 }, "", document.URL);
});
I think that your problem is that grep uses some output buffering. Try
tail -f file | stdbuf -o0 grep my_pattern
it will set output buffering mode of grep to unbuffered.
In addition to Richard Simões answer you can also use the Page Visibility API.
if (!document.hidden) {
// do what you need
}
This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.
document.hidden
var day = value.Date; // a DateTime that will just be whole days
var time = value.TimeOfDay; // a TimeSpan that is the duration into the day
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
I don't know why this question was reopened but here is a tidyverse
option.
x %>%
arrange(desc(value)) %>%
mutate(variable=fct_reorder(variable,value)) %>%
ggplot(aes(variable,value,fill=variable)) + geom_bar(stat="identity") +
scale_y_continuous("",label=scales::percent) + coord_flip()
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:
<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>
Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:
$_POST['letter']
To get the value chosen.
very simple
<img onload="loaded(this, 'success')" onerror="error(this,
'error')" src="someurl" alt="" />
function loaded(_this, status){
console.log(_this, status)
// do your work in load
}
function error(_this, status){
console.log(_this, status)
// do your work in error
}
I had a similar issue. In my case VPN proxy app such as Psiphon ? changed the proxy setup in windows so follow this :
in Windows 10, search change proxy settings and turn of use proxy server in the manual proxy
def giveText(num):
pairs={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',
11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',
30:'thirty',40:'fourty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',0:''} # this and above 2 lines are actually single line
return pairs[num]
def toText(num,unit):
n=int(num)# this line can be removed
ans=""
if n <=20:
ans= giveText(n)
else:
ans= giveText(n-(n%10))+" "+giveText((n%10))
ans=ans.strip()
if len(ans)>0:
return " "+ans+" "+unit
else:
return " "
num="99,99,99,999"# use raw_input()
num=num.replace(",","")# to remove ','
try:
num=str(int(num)) # to check valid number
except:
print "Invalid"
exit()
while len(num)<9: # i want fix length so no need to check it again
num="0"+num
ans=toText( num[0:2],"Crore")+toText(num[2:4],"Lakh")+toText(num[4:6],"Thousand")+toText(num[6:7],"Hundred")+toText(num[7:9],"")
print ans.strip()
The accepted answer - git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>)
- is very close, but I noticed that it got the status wrong for deletions. I added a file in a branch, and yet this command (using --name-status
) gave the file I deleted "A" status and the file I added "D" status.
I had to use this command instead:
git diff --name-only $(git merge-base <notMainDev> <mainDev>)
In jQuery I mostly use:
$("#element").trigger("change");
You can use 'input' event, that occurs when an element gets user input.
$(document).on('input', '#input_id', function() {
// this will fire all possible change actions
});
documentation from w3
UPDATE
By Android Support Library 23.2 update, all WRAP_CONTENT should work correctly.
Please update version of a library in gradle file.
compile 'com.android.support:recyclerview-v7:23.2.0'
Original Answer
As answered on other question, you need to use original onMeasure() method when your recycler view height is bigger than screen height. This layout manager can calculate ItemDecoration and can scroll with more.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
// If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
if (height < heightSize && width < widthSize) {
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
// For adding Item Decor Insets to view
super.measureChildWithMargins(view, 0, 0);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
view.measure(childWidthSpec, childHeightSpec);
// Get decorated measurements
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
original answer : https://stackoverflow.com/a/28510031/1577792
On Mac: Eclipse -> Preferences -> Remote Systems -> Files -> click Show Hidden Files.
The excellent book "Algorithm Design Manual" by Skienna contains a huge repository of Algorithms and Data structure.
For tons of problems, data structures and algorithm are described, compared, and discusses the practical usage. The author also provides references to implementations and the original research papers.
The book is great to have it on your desk if you search the best data structure for your problem to solve. It is also very helpful for interview preparation.
Another great resource is the NIST Dictionary of Data structures and algorithms.
A more modern approach to waiting for elements:
while(!document.querySelector(".my-selector")) {
await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded
Note that this code would need to be wrapped in an async function.
I think you cannot get it as String
but you can get it as int
by get resource id
:
int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());
/WebKit/.test(navigator.userAgent)
— that's it.
Use window.open()
:
<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
Share Page
</a>
This will create a link titled Share Page
which opens the current url in a new window with a height of 570 and width of 520.
Unfortunately the examples above didn't work for me in Chrome.
I came up with the below solution where you can specify the max height in PXs of each page. This will then splits the table into separate tables when the rows equal that height.
$(document).ready(function(){
var MaxHeight = 200;
var RunningHeight = 0;
var PageNo = 1;
$('table.splitForPrint>tbody>tr').each(function () {
if (RunningHeight + $(this).height() > MaxHeight) {
RunningHeight = 0;
PageNo += 1;
}
RunningHeight += $(this).height();
$(this).attr("data-page-no", PageNo);
});
for(i = 1; i <= PageNo; i++){
$('table.splitForPrint').parent().append("<div class='tablePage'><hr /><table id='Table" + i + "'><tbody></tbody></table><hr /></div>");
var rows = $('table tr[data-page-no="' + i + '"]');
$('#Table' + i).find("tbody").append(rows);
}
$('table.splitForPrint').remove();
});
You will also need the below in your stylesheet
div.tablePage {
page-break-inside:avoid; page-break-after:always;
}
Keep radio buttons hidden, and on clicking of images, select them using JavaScript and style your image so that it look like selected. Here is the markup -
<div id="radio-button-wrapper">
<span class="image-radio">
<input name="any-name" style="display:none" type="radio"/>
<img src="...">
</span>
<span class="image-radio">
<input name="any-name" style="display:none" type="radio"/>
<img src="...">
</span>
</div>
and JS
$(".image-radio img").click(function(){
$(this).prev().attr('checked',true);
})
CSS
span.image-radio input[type="radio"]:checked + img{
border:1px solid red;
}
This is likely already out there, but I was playing with renaming fields while searching out a solution and tried this on a whim. Worked for my purposes.
Table1$FieldNewName <- Table1$FieldOldName
Table1$FieldOldName <- NULL
Edit begins here....
This works as well.
df <- rename(df, c("oldColName" = "newColName"))
Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:
echo CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT
I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.
It looks that in awk, string can be concatenated by printing variable next to each other:
echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal
I tried http://gitstats.sourceforge.net/, starts are very interesting.
Once git clone git://repo.or.cz/gitstats.git
is done, go to that folder and say gitstats <git repo location> <report output folder>
(create a new folder for report as this generates lots of files)
Here is a quick list of stats from this:
Thanks for the help. This is what I ended up doing in order to make it work.
CREATE VIEW V AS
SELECT *
FROM ((POP NATURAL FULL OUTER JOIN FOOD)
NATURAL FULL OUTER JOIN INCOME);
On Ubuntu, this can also be caused by incorrect permissions. I chmod 755 Logs/
which fixed the issue.
retrying
: tenacity
and backoff
(2020 update)The retrying library was previously the way to go, but sadly it has some bugs and it hasn't got any updates since 2016. Other alternatives seem to be backoff and tenacity. During the time of writing this, the tenacity had more GItHub stars (2.3k vs 1.2k) and was updated more recently, hence I chose to use it. Here is an example:
from functools import partial
import random # producing random errors for this example
from tenacity import retry, stop_after_delay, wait_fixed, retry_if_exception_type
# Custom error type for this example
class CommunicationError(Exception):
pass
# Define shorthand decorator for the used settings.
retry_on_communication_error = partial(
retry,
stop=stop_after_delay(10), # max. 10 seconds wait.
wait=wait_fixed(0.4), # wait 400ms
retry=retry_if_exception_type(CommunicationError),
)()
@retry_on_communication_error
def do_something_unreliable(i):
if random.randint(1, 5) == 3:
print('Run#', i, 'Error occured. Retrying.')
raise CommunicationError()
for i in range(100):
do_something_unreliable(i)
The above code outputs something like:
Run# 3 Error occured. Retrying.
Run# 5 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 6 Error occured. Retrying.
Run# 10 Error occured. Retrying.
.
.
.
More settings for the tenacity.retry
are listed on the tenacity GitHub page.
Edit your /etc/postgresql/9.3/main/postgresql.conf
, and change the lines as follows.
Note: If you didn't find the postgresql.conf
file, then just type $locate postgresql.conf
in a terminal
#log_directory = 'pg_log'
to log_directory = 'pg_log'
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
to log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
#log_statement = 'none'
to log_statement = 'all'
#logging_collector = off
to logging_collector = on
Optional: SELECT set_config('log_statement', 'all', true);
sudo /etc/init.d/postgresql restart
or sudo service postgresql restart
Fire query in postgresql select 2+2
Find current log in /var/lib/pgsql/9.2/data/pg_log/
The log files tend to grow a lot over a time, and might kill your machine. For your safety, write a bash script that'll delete logs and restart postgresql server.
Thanks @paul , @Jarret Hardie , @Zoltán , @Rix Beck , @Latif Premani
The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.
The problem might be your split()
call. Try just split(" ")
without the square brackets.
I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.
Take byteStr2byteArray() as an example:
<?php
function byteStr2byteArray($s) {
return array_slice(unpack("C*", "\0".$s), 1);
}
$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);
for($i=0;$i<count($byte_array);$i++)
{
printf("0x%02x ", $byte_array[$i]);
}
?>
In Swift that would look like this:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)
Swift 3 version:
let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)
Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)
Since version 4 the closest alternative is child_process.execSync
method:
const {execSync} = require('child_process');
let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');
?? Note that
execSync
call blocks event loop.
First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.
$(".myselect")
To answer your question though, there are a few ways to change the select elements value in jQuery
// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0');
// sets selected index of a select box to the option with the value ""
$("select#elem").val('');
// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;
// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
You can just pass a list of the two points you want to connect to plt.plot
. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5, 1, -0.5, -1]
plt.plot(x,y, 'ro')
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connectpoints(x,y,0,1)
connectpoints(x,y,2,3)
plt.axis('equal')
plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point i
to point i+1
, we can just put it in a for loop:
import numpy as np
for i in np.arange(0,len(x),2):
connectpoints(x,y,i,i+1)
In that case of always connecting point i
to point i+1
, you could simply do:
for i in np.arange(0,len(x),2):
plt.plot(x[i:i+2],y[i:i+2],'k-')
There is a change in syntax from Python 2 to Python 3. In Python 2,
print "Hello, World!"
will work but in Python 3, use parentheses as
print("Hello, World!")
This is equivalent syntax to Scala and near to Java.
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
Quick and in some cases error-prone solution:
Find Regexp: (?sm)(.*?)([^\n]*\b(class|interface|enum)\b.*)
Replace: $1/**\n * \n * @author <a href="mailto:[email protected]">John Smith</a>\n */\n$2
This will add the header to the first encountered class/interface/enum in the file. Class should have no existing header yet.
No, there isn't.
The point of on()
is its other overloads, and the ability to handle events that don't have shortcut methods.
If you would like to purposely link your project A in Release against another project B in Debug, say to keep the overall performance benefits of your application while debugging, then you will likely hit this error. You can fix this by temporarily modifying the preprocessor flags of project B to disable iterator debugging (and make it match project A):
In Project B's "Debug" properties, Configuration Properties -> C/C++ -> Preprocessor, add the following to Preprocessor Definitions:
_HAS_ITERATOR_DEBUGGING=0;_ITERATOR_DEBUG_LEVEL=0;
Rebuild project B in Debug, then build project A in Release and it should link correctly.
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
I wrote a program with wpf
and used Database for showing images and this is my code:
SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
Initial Catalog=Payam;
Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from news", con);
DataTable dt = new DataTable();
da.Fill(dt);
string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;
Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S
I wanted to make public once me too a google code fix and got the same error. Started with This video, but at Save and publish got an error. I have seen there are several question regarding to this. Some are Windows users, those are the most lucky, because usually no problems with permissions and some are Linux users.
I have a mac for mobile development use and very often meet this problems. The source for this problems is the "platform independent" solutions, which doesn't care enough for mac and they don't have access to keychain, where are stored the certificates, .pem files and so on.
All I wanted is to not make any environment settings, nor command line, just simple GUI based clicks, like a regular user.
Half part was done with Eclipse Git plugin, second part (push to Github) was done with Mac Github
Nice and easy :)
All can be done with with that native appp if I would start to learn it, I just need the push functionality from him.
Hoping it will help a mac user once.