You can also do a simple check using function,
$scope.isNullOrEmptyOrUndefined = function (value) {
return !value;
}
just use the jQuery datepicker UI library and convert both your strings into date format, then you can easily compare. following link might be useful
https://stackoverflow.com/questions/2974496/jquery-javascript-convert-date-string-to-date
cheers..!!
When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile
ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*
to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1
contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:
cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.
In a debug compilation, Assert
takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
If you compile in Release, all Debug.Assert
's are automatically left out.
When I went to Google fonts all they gave me were true type font files .ttf
and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -
I had great success using the following method:
I selected the Add Fonts button, leaving the default options, added all of my .ttf
that Google gave me for Open Sans
(which was like 10, I chose a lot of options...).
Then I selected the Convert button.
Heres the best part!
They gave me a zip file with all the font format files I selected, .ttf
, .woff
and .eot
. Inside that zip file they had a demo.html
file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.
@font-face
I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face
but then I noticed that this demo.html
came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face
so I was able to quickly, and easily, copy paste this into my project -
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
font-weight: 300;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
font-weight: 600;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Regular.eot');
src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Light.eot');
src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Italic.eot');
src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
font-weight: 600;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
font-weight: 800;
font-style: normal;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
font-weight: 800;
font-style: italic;
}
@font-face {
font-family: 'Open Sans';
src: url('fonts/Open_Sans/OpenSans-Bold.eot');
src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
font-weight: bold;
font-style: normal;
}
The demo.html
also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face
has been used properly -
html, body{
margin: 0;
font-family: 'Open Sans';
}
.banner h1{
font-size: 43px;
font-weight: 700;
}
.banner p{
font-size: 24px;
font-weight: 300;
font-style: italic;
}
since python 3.5 you can use *
iterable unpacking operator:
user_list = [*your_iterator]
but the pythonic way to do it is:
user_list = list(your_iterator)
There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:
let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');
Without support for ES6 you can try using objects:
var x = new Object();
x["Key"] = "Value";
However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.
You can also use this stored procedure if you only want to truncate all tables in a specific schema:
-- =============================================
-- Author: Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
@schema nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @table nVARCHAR(255)
DECLARE db_cursor CURSOR FOR
select t.name
from sys.tables t inner join
sys.schemas s on
t.schema_id=s.schema_id
where s.name=@schema
order by 1
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
declare @sql nvarchar(1000)
set @sql = 'truncate table [' + @schema + '].[' + @table + ']'
exec sp_sqlexec @sql
FETCH NEXT FROM db_cursor INTO @table
END
CLOSE db_cursor
DEALLOCATE db_cursor
END
GO
In operating systems like Ubuntu python comes preinstalled. So the default version is python 2.7 you can confirm the version by typing below command in your terminal
python -V
if you installed it but didn't set default version you will see
python 2.7
in terminal. I will tell you how to set the default python version in Ubuntu.
A simple safe way would be to use an alias. Place this into ~/.bashrc or ~/.bash_aliases file:
alias python=python3
After adding the above in the file, run the command below:
source ~/.bash_aliases
or source ~/.bashrc
now check python version again using python -V
if python version 3.x.x one, then the error is in your syntax like using print with parenthesis. change it to
test = input("enter the test")
print(test)
This can be done by two ways according to your Android OS.
android:largeHeap="true"
in application tag of Android manifest to request a larger heap size, but this will not work on any pre Honeycomb devices.VMRuntime.getRuntime().setMinimumHeapSize(BIGGER_SIZE);
Before Setting HeapSize make sure that you have entered the appropriate size which will not affect other application or OS functionality. Before settings just check how much size your app takes & then set the size just to fulfill your job. Dont use so much of memory otherwise other apps might affect.
Reference: http://dwij.co.in/increase-heap-size-of-android-application
You absolutely can, I use this approach a lot w/ both JavaScript and PHP.
Field definition:
<input type="hidden" name="foo" value="<?php echo $var;?>" />
Access w/ PHP:
$_GET['foo'] or $_POST['foo']
Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php
Cheers!
The issue here is your version of AngularJS; ng-attr
is not working due to the fact that it was introduced in version 1.1.4. I am unsure as to why title="{{product.shortDesc}}"
isn't working for you, but I imagine it is for similar reasons (old Angular version). I tested this on 1.2.9 and it is working for me.
As for the other answers here, this is NOT among the few use cases for ng-attr
! This is a simple double-curly-bracket situation:
<a title="{{product.shortDesc}}" ng-bind="product.shortDesc" />
res.writeHead(404, {'Content-Type': 'text/plain'}); // <- redirect
res.write("Looked everywhere, but couldn't find that page at all!\n"); // <- content!
res.end(); // that's all!
res.writeHead(302, {'Location': 'https://example.com' + req.url});
res.end();
Just consider where you use this (e.g. only for http request), so you don't get endless redirects ;-)
Here's one that accounts for ties.
Name Salary
Jim 6
Foo 5
Bar 5
Steve 4
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))
Result --> Bar 5, Foo 5
EDIT: I took Manoj's second post, tweaked it, and made it a little more human readable. To me n-1 is not intuitive; however, using the value I want, 2=2nd, 3=3rd, etc. is.
/* looking for 2nd highest salary -- notice the '=2' */
SELECT name,salary FROM employees
WHERE salary = (SELECT DISTINCT(salary) FROM employees as e1
WHERE (SELECT COUNT(DISTINCT(salary))=2 FROM employees as e2
WHERE e1.salary <= e2.salary)) ORDER BY name
Result --> Bar 5, Foo 5
In my case previous version was 3.2. I have upgraded to 3.6 but data files was not compatible to new version so I removed all data files as it was not usable for me and its works.
You can check logs using /var/log/mongodb
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
When you want it to validate (in XML/XHTML - thanks, Loren Segal).
AND
and OR
are just syntactic sugar for &&
and ||
, like in JavaScript, or other C styled syntax languages.
It appears AND
and OR
have lower precedence than their C style equivalents.
if I understand you right (not sure), the start
parameter /D should help you:
start "cmd" /D %PathName% %comd%
/D sets the start-directory (see start /?)
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
Check your file permissions
for the correct linux user for classUser.php
Format cell
.Custom
.General
and insert this formol ----> "k"@Red Gate's .NET Reflector is a pretty awesome tool that has helped me out more than a few times. The plus side of this utility outside of easily showing you MSIL is that you can analyze a lot of third-party DLLs and have the Reflector take care of converting MSIL to C# and VB.
I'm not promising the code will be as clear as source but you shouldn't have much trouble following it.
/usr/bin/swiftc --version
No, you cannot put an assignment inside a lambda because of its own definition. If you work using functional programming, then you must assume that your values are not mutable.
One solution would be the following code:
output = lambda l, name: [] if l==[] \
else [ l[ 0 ] ] + output( l[1:], name ) if l[ 0 ].name == name \
else output( l[1:], name ) if l[ 0 ].name == "" \
else [ l[ 0 ] ] + output( l[1:], name )
The problem is indeed the register key that is missing. It can be created manually
OR
it can be created automagically by running the program as administrator once. That will give the program the permissions required, and when it will be ran as normal it will still work correctly.
How about this:
import sys
import subprocess
theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate() # ^^^^^^^^^^^^
This tells subprocess
to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.
Additionally, this will search the PATH for "myscript.py" - which could be desirable.
I cloned the following: https://github.com/google/play-licensing
Then I imported that into my project.
Also possible is to fix this with np.arange() instead of range which works for float numbers:
import numpy as np
for i in np.arange(c/10):
You can use RegularExpressionValidator for this. below is the sample code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="TextBox1" runat="server"
ErrorMessage="Only Numbers allowed"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>
above TextBox only allowed integer to be entered because in RegularExpressionValidator has field called ValidationExpression, which validate the TextBox. However, you can modify as per your requirement.
You can see more example in MVC and Jquery here.
$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
just in case someone is getting NullPointerException
, you need to get the context inside onCreate().
Service
is a Context
, so do this:
@Override
public void onCreate() {
super.onCreate();
context = this;
}
All i needed was:
.modal-header{
background-color:#0f0;
}
.modal-content {
overflow:hidden;
}
overflow: hidden
to keep the color inside the border-radius
On the ViewController you want as your modal popup, make the background color of the root UIView clear. Tip: Do not use the root UIView as your popup. Add a new UIView that is smaller to be your popup.
Create a Segue to the ViewController that has your popup. Select "Present Modally".
Select the Segue and change Presentation to "Over Current Context":
Select the ViewController Scene that is your popup. In Attributes Inspector, under View Controller section, set Presentation to "Over Current Context":
Either method will work. That should do it!
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')
Just trying to simplify the code using Connectivity Package in Flutter.
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
} else {
// I am not connected to the internet
}
So some days I lack brain cells and:
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/CustomSwitchStyle"/>
does not apply the theme because style is incorrect. I was supposed to use app:theme :P
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/CustomSwitchStyle"/>
Whoopsies. This post was what gave me insight into my mistake...hopefully if someone stumbles across this it will help them like it did me. Thank you Gaëtan Maisse for your answer
All the parameters after ?
can be accessed using $_GET
array. So,
echo $_GET['email'];
will extract the emails from urls.
You can use select2 plugin for creating such a filter. With this lot's of coding work can be avoided. You can grab the plugin from https://select2.github.io/
This plugin is much simple to apply and even advanced work can be easily done with it. :)
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
I think this simple code would work:
if(!(image_array<=0)){
//Specify function needed
}
By doing so you'd be able to control any action of the framed page, which you cannot. Same-domain origin policy applies.
One way I like to use is Vanilla JavaScript with template literal:
var templateLiteral = [`
<!-- HTML_CODE_COMES_HERE -->
`]
var head = document.querySelector("head");
head.innerHTML = templateLiteral;
With Postman, to test HTTP post actions with a raw JSON data payload, select the raw
option and set the following header parameters:
Content-Type: application/json
Also, be sure to wrap any strings used as keys/values in your JSON payload in double quotes.
The body-parser
package will parse multi-line raw JSON payloads just fine.
{
"foo": "bar"
}
Tested in Chrome v37 and v41 with the Postman v0.8.4.13 extension (body-parser
v1.12.2 and express
v4.12.3) with the setup below:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// ... Your routes and methods here
By default mesh
will color surface values based on the (default) jet
colormap (i.e. hot is higher). You can additionally use surf
for filled surface patches and set the 'EdgeColor'
property to 'None'
(so the patch edges are non-visible).
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
% surface in 3D
figure;
surf(Z,'EdgeColor','None');
2D map: You can get a 2D map by switching the view
property of the figure
% 2D map using view
figure;
surf(Z,'EdgeColor','None');
view(2);
... or treating the values in Z
as a matrix, viewing it as a scaled image using imagesc
and selecting an appropriate colormap.
% using imagesc to view just Z
figure;
imagesc(Z);
colormap jet;
The color pallet of the map is controlled by colormap(map)
, where map
can be custom or any of the built-in colormaps provided by MATLAB:
Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As @Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:
figure;
surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
axis equal;
axis off;
Try this:
/**
* The template for displaying demo page
*
* template name: demo template
*
*/
try this
ArrayList<ArrayList<String>> PriceModelList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceQtyList = new ArrayList<>();
ArrayList<ArrayList<String>> PriceTotalList = new ArrayList<>();
for (int i = 0; i < CustomerNames.length; i++) {
PriceModelList.add(new ArrayList<String>());
String[] PriceModel = {"s6", "s7", "note4", "note5", "j5", "j6"};
for (int j = 0; j < PriceModel.length; j++) {
PriceModelList.get(i).add(PriceModel[j]);
}
PriceQtyList.add(new ArrayList<String>());
String[] PriceQut = {"12", "13", "21", "15", "43", "21"};
for (int k = 0; k < PriceQut.length; k++) {
PriceQtyList.get(i).add(PriceQut[k]);
}
PriceTotalList.add(new ArrayList<String>());
String[] PriceTotal = {"1323", "1312321", "43123212", "43434", "12312", "43322"};
for (int m = 0; m < PriceTotal.length; m++) {
PriceTotalList.get(i).add(PriceTotal[m]);
}
}
ArrayList<ArrayList<ArrayList<String>>> CustomersShoppingLists = new ArrayList<>();
CustomersShoppingLists.add(PriceModelList);
CustomersShoppingLists.add(PriceQtyList);
CustomersShoppingLists.add(PriceTotalList);
Years ago I wrote a colored stream handler for my own use. Then I came across this page and found a collection of code snippets that people are copy/pasting :-(. My stream handler currently only works on UNIX (Linux, Mac OS X) but the advantage is that it's available on PyPI (and GitHub) and it's dead simple to use. It also has a Vim syntax mode :-). In the future I might extend it to work on Windows.
To install the package:
$ pip install coloredlogs
To confirm that it works:
$ coloredlogs --demo
To get started with your own code:
$ python
> import coloredlogs, logging
> coloredlogs.install()
> logging.info("It works!")
2014-07-30 21:21:26 peter-macbook root[7471] INFO It works!
The default log format shown in the above example contains the date, time, hostname, the name of the logger, the PID, the log level and the log message. This is what it looks like in practice:
NOTE: When using Git Bash w/ MinTTY
Git Bash on windows has some documented quirks: Winpty and Git Bash
Which for ANSI escape codes and for ncurses style character rewriting and animations, you need to prefix commands with winpty
.
$ winpty coloredlogs --demo
$ winpty python your_colored_logs_script.py
I'm using this method -> based on API Demos to get my Preview Size:
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio=(double)h / w;
if (sizes == null) return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
As you can see you have to input width and height of your screen. This method will calculate screen ratio based on those values and then from the list of supportedPreviewSizes it will choose the best for you from avaliable ones. Get your supportedPreviewSize list in place where Camera object isn't null by using
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
And then on in onMeasure you can get your optimal previewSize like that:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
And then (in my code in surfaceChanged method, like I said I'm using API Demos structure of CameraActivity code, you can generate it in Eclipse):
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
And one hint for you, because I did almost the same app like you. Good practice for Camera Activity is to hide StatusBar. Applications like Instagram are doing it. It reduces your screen height value and change your ratio value. It is possible to get strange Preview Sizes on some devices (your SurfaceView will be cut a little)
And to answer your question, how to check if your preview ratio is correct? Then get height and width of parameters that you set in:
mCamera.setParameters(parameters);
your set ratio is equal to height/width. If you want camera to look good on your screen then height/width ratio of parameters that you set to camera must be the same as height(minus status bar)/width ratio of your screen.
On Debian, using openjdk version "1.8.0_212", I found cacerts here:
/etc/ssl/certs/java/cacerts
Sure would be handy if there was a standard command that would print out this path.
1) You can wrap your text as CDATA like this:
<mytag>
<![CDATA[Your text goes here. Btw: 5<6 and 6>5]]>
</mytag>
see http://www.w3schools.com/xml/xml_cdata.asp
2) As already someone said: Escape those chars. E.g. like so:
5<6 and 6>5
To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...
There was no year 0000 and there is no month 00 or day 00. I suggest you try
0001-01-01 00:00:00
While a year 0 has been defined in some standards, it is more likely to be confusing than useful IMHO.
I know it's old question but if you really need use $scope.$applyAsync();
input type="range" min="0" max="50" value="0" style="margin-left: 6%;width: 88%;background-color: whitesmoke;"
above code changes range input style.....
You can do so from within vim and use its own windows or tabs.
One way to go is to utilize the built-in file explorer; activate it via :Explore
, or :Texplore
for a tabbed interface (which I find most comfortable).
:Texplore
(and :Sexplore
) will also guard you from accidentally exiting the current buffer (editor) on :q
once you're inside the explorer.
To toggle between open tabs when using tab pages use gt
or gT
(next tab and previous tab, respectively).
See also Using tab pages on the vim wiki.
The sequence of characters between < and > uniquely refer to a header, which isn't necessarily a file. Implementations are pretty much free to use the character sequence as they wish. (Mostly, however, just treat it as a file name and do a search in the include path, as the other posts state.)
If the #include "file"
form is used, the implementation first looks for a file of the given name, if supported. If not (supported), or if the search fails, the implementation behaves as though the other (#include <file>
) form was used.
Also, a third form exists and is used when the #include
directive doesn't match either of the forms above. In this form, some basic preprocessing (such as macro expansion) is done on the "operands" of the #include
directive, and the result is expected to match one of the two other forms.
A threadpool with no dependencies outside of STL is entirely possible. I recently wrote a small header-only threadpool library to address the exact same problem. It supports dynamic pool resizing (changing the number of workers at runtime), waiting, stopping, pausing, resuming and so on. I hope you find it useful.
public static String shuffle(String s) {
List<String> letters = Arrays.asList(s.split(""));
Collections.shuffle(letters);
StringBuilder t = new StringBuilder(s.length());
for (String k : letters) {
t.append(k);
}
return t.toString();
}
I know this is an old question, but it hasn't been correctly addressed, so I'm answering it for others who may run into this problem.
By default Oracle's ODP.net binds variables by position, and treats each position as a new variable.
Treating each copy as a different variable and setting it's value multiple times is a workaround and a pain, as furman87 mentioned, and could lead to bugs, if you are trying to rewrite the query and move things around.
The correct way is to set the BindByName property of OracleCommand to true as below:
var cmd = new OracleCommand(cmdtxt, conn);
cmd.BindByName = true;
You could also create a new class to encapsulate OracleCommand setting the BindByName to true on instantiation, so you don't have to set the value each time. This is discussed in this post
The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain UNIQUE values and column cannot contain NULL Values.
-- DROP current primary key
ALTER TABLE tblPersons DROP CONSTRAINT <constraint_name>
Example:
ALTER TABLE tblPersons
DROP CONSTRAINT P_Id;
-- ALTER TABLE tblpersion
ALTER TABLE tblpersion add primary key (P_Id,LastName)
This is the check on which it fails:
Which says
def _assert_all_finite(X):
"""Like assert_all_finite, but only for ndarray."""
X = np.asanyarray(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) space np.isfinite to prevent
# false positives from overflow in sum method.
if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
and not np.isfinite(X).all()):
raise ValueError("Input contains NaN, infinity"
" or a value too large for %r." % X.dtype)
So make sure that you have non NaN values in your input. And all those values are actually float values. None of the values should be Inf either.
pd.set_option('display.max_rows', 500)
df
Does not work in Jupyter!
Instead use:
pd.set_option('display.max_rows', 500)
df.head(500)
For me it worked as Kumar Jaggal but: steps 1, 2, 3, the same 4. py -m setup.py install
There are a few pieces to doing this, assuming each list does not contain duplicates, Name is a unique identifier, and neither list is ordered.
First create an append extension method to get a single list:
static class Ext {
public static IEnumerable<T> Append(this IEnumerable<T> source,
IEnumerable<T> second) {
foreach (T t in source) { yield return t; }
foreach (T t in second) { yield return t; }
}
}
Thus can get a single list:
var oneList = list1.Append(list2);
Then group on name
var grouped = oneList.Group(p => p.Name);
Then can process each group with a helper to process one group at a time
public Person MergePersonGroup(IGrouping<string, Person> pGroup) {
var l = pGroup.ToList(); // Avoid multiple enumeration.
var first = l.First();
var result = new Person {
Name = first.Name,
Value = first.Value
};
if (l.Count() == 1) {
return result;
} else if (l.Count() == 2) {
result.Change = first.Value - l.Last().Value;
return result;
} else {
throw new ApplicationException("Too many " + result.Name);
}
}
Which can be applied to each element of grouped
:
var finalResult = grouped.Select(g => MergePersonGroup(g));
(Warning: untested.)
@noskio is correct... it just means that simplejson
isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install
tool. with it, you can install it as easily as: easy_install simplejson
UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson
), only it can also uninstall apps.
For Windows, an easy-and-quick tool is LocMetrics.
Create a Dockerfile
#
# Build stage
#
FROM maven:3.6.3-jdk-11-slim AS build
WORKDIR usr/src/app
COPY . ./
RUN mvn clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
ARG JAR_NAME="project-name"
WORKDIR /usr/src/app
EXPOSE ${HTTP_PORT}
COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar
CMD ["java","-jar", "./app.jar"]
I am not sure whether I understood your intentions correctly, but let's see if this one helps.
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
I am solving that problem by opening Services then start running Sql Server (Sqlexpress) service.
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.
The official way is:
docker rm `docker ps -aq`
The Docker maintainers have indicated there will be no command for this - and you compose the commands like that:
We have discussed this before and prefer users to use the above line without having to add additional code to Docker.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing three object arrays
Object[] array1 = new Object[] { 1, 123 };
Object[] array2 = new Object[] { 1, 123, 22, 4 };
Object[] array3 = new Object[] { 1, 123 };
// comparing array1 and array2
boolean retval=Arrays.equals(array1, array2);
System.out.println("array1 and array2 equal: " + retval);
System.out.println("array1 and array2 equal: " + array1.equals(array2));
// comparing array1 and array3
boolean retval2=Arrays.equals(array1, array3);
System.out.println("array1 and array3 equal: " + retval2);
System.out.println("array1 and array3 equal: " + array1.equals(array3));
}
}
Here is the output:
array1 and array2 equal: false
array1 and array2 equal: false
array1 and array3 equal: true
array1 and array3 equal: false
Seeing this kind of problem I would personally go for Arrays.equals(array1, array2)
as per your question to avoid confusion.
Semantically there is no difference between these cases in LDAP.
You may have to go from DateTime to LocalDate.
Using Joda Time:
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();
If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the tr
utility, or to Perl if preferred:
wc -l < log.txt | tr -d '\n'
wc -l < log.txt | perl -pe 'chomp'
You can also use command substitution to remove the trailing newline:
echo -n "$(wc -l < log.txt)"
printf "%s" "$(wc -l < log.txt)"
If your expected output may contain multiple lines, you have another decision to make:
If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:
printf "%s" "$(< log.txt)"
If you want to strictly remove THE LAST newline character from a file, use Perl:
perl -pe 'chomp if eof' log.txt
Note that if you are certain you have a trailing newline character you want to remove, you can use head
from GNU coreutils to select everything except the last byte. This should be quite quick:
head -c -1 log.txt
Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using cat
and the 'show-all' flag -A
. The dollar sign character will indicate the end of each line:
cat -A log.txt
If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.
With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.
Below is the summary of the style I have defined for emailing the code snippets.
Do not check spelling or grammar, Border:
Box: (Single solid line, Orange, 0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted
If you want to check if a string contains substring or not using regex, the closest you can do is by using find() -
private static final validPattern = "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.
Note the difference between matches() and find(), matches() return true if the whole string matches the given pattern. find() tries to find a substring that matches the pattern in a given input string. Also by using find() you don't have to add extra matching like - (?s).* at the beginning and .* at the end of your regex pattern.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it's not less than 2.4. What you should have had was:
if sys.version_info **<=** (2, 4):
, not
if sys.version_info < (2, 4):
Installing freetype:
sudo apt update && sudo apt install freetype2-demos
By using org.apache.http.client.HttpClient also you can easily do this with more readable way as below.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
Within try catch you can insert
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
I had a same issue .I removed the extension from the file name.Example my file name was saved as xyz. csv. i saved it as xyz.
You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).
Take a look at the following link for more information.
This is exactly what the Validated/Validating events were designed for.
Here's the MSDN article on the topic: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx
The TL;DR version: check the .Text property in the Validating event and set e.Cancel=True
when the data is invalid.
When you set e.Cancel=True, the user can't leave the field, but you will need to give them some kind of feedback that something's wrong. I change the box's background color to light red to indicate a problem. Make sure to set it back to SystemColors.Window
when Validating is called with a good value.
I had a similar problem after copying the angular2-quickstart folder (including node_modules) to create the angular2-tour-of-heroes folder. This was wierd because the original was compiling fine but the copy was not...
npm run tsc
I was able to resolve the issue by deleting the node_modules folder and re-running npm install.
This was a surprise to me, so I did a diff between the 2 folders...
diff -rw angular2-quickstart/node_modules/ angular2-tour-of-heroes/node_modules/
there were a LOT of differences, a lot of 'where' diffs in the package.json files like this:-
diff -rw angular2-quickstart/node_modules/yargs/package.json angular2-tour-of-heroes/node_modules/yargs/package.json
5c5
< "/Users/michael/Tutorials/angular2/angular2-quickstart/node_modules/lite-server"
---
> "/Users/michael/Tutorials/angular2/angular2-tour-of-heroes/node_modules/lite-server"
...which kind of makes sense but there were also some like this:-
diff -rw angular2-quickstart/node_modules/utf-8-validate/build/gyp-mac-tool angular2-tour-of-heroes/node_modules/utf-8-validate/build/gyp-mac-tool
607c607,608
< return {k: self._ExpandVariables(data[k], substitutions) for k in data}
---
> return dict((k, self._ExpandVariables(data[k],
> substitutions)) for k in data)
...which I don't understand at all.
Oh well, Hope this helps.
Syntax:
CASE value WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
mysql> SELECT CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END;
+-------------------------------------------------------------+
| CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false |
+-------------------------------------------------------------+
I am use:
SELECT act.*,
CASE
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND lises.session_date >= now()
LEFT JOIN session AS ses ON ses.activity_id = act.id AND ses.session_date >= now()
WHERE act.id
I was able to came up with a couple of "one line" solutions, for example:
obj.map(o -> (Runnable) () -> o.setAvailable(true))
.orElse(() -> logger.fatal("Object not available"))
.run();
or
obj.map(o -> (Consumer<Object>) c -> o.setAvailable(true))
.orElse(o -> logger.fatal("Object not available"))
.accept(null);
or
obj.map(o -> (Supplier<Object>) () -> {
o.setAvailable(true);
return null;
}).orElse(() () -> {
logger.fatal("Object not available")
return null;
}).get();
It doesn't look very nice, something like orElseRun
would be much better, but I think that option with Runnable is acceptable if you really want one line solution.
Install and use this mysql statistical functions: http://www.xarg.org/2012/07/statistical-functions-in-mysql/
After that, calculate median is easy:
SELECT median(val) FROM data;
I go this error fixed by using the below code. I had setup the SPARK_HOME though. You may follow this simple steps from eproblems website
spark_home = os.environ.get('SPARK_HOME', None)
OK, after days struggling with this issue, I finally fixed it.
Simple!
Apparently there was a permission error with my local system that the C# compiler (csc.exe) could not access some resources and source codes.
In order to change your AppPool identity follow steps given here: http://learn.iis.net/page.aspx/624/application-pool-identities/
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
There are a few ways. One of the simplest is to create a my-paths.pth
file (as described here). This is just a file with the extension .pth
that you put into your system site-packages
directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/
and it will add that directory to the path.
You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path
. See the documentation.
Note that no matter what you do, sys.path
contains directories not files. You can't "add a file to sys.path
". You always add its directory and then you can import the file.
You can use slice notation with steps:
>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.
In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.
Today, just say object-fit: contain. Support is everything but IE: http://caniuse.com/#feat=object-fit
if you're using scala and know the generic type at compile time, but don't want to manually pass TypeReference everywhere in all your api l ayers, you can use the following code (with jackson 2.9.5):
def read[T](entityStream: InputStream)(implicit typeTag: WeakTypeTag[T]): T = {
//nathang: all of this *crazy* scala reflection allows us to handle List[Seq[Map[Int,Value]]]] without passing
// new TypeReference[List[Seq[Map[Int,Value]]]]](){} to the function
def recursiveFindGenericClasses(t: Type): JavaType = {
val current = typeTag.mirror.runtimeClass(t)
if (t.typeArgs.isEmpty) {
val noSubtypes = Seq.empty[Class[_]]
factory.constructParametricType(current, noSubtypes:_*)
}
else {
val genericSubtypes: Seq[JavaType] = t.typeArgs.map(recursiveFindGenericClasses)
factory.constructParametricType(current, genericSubtypes:_*)
}
}
val javaType = recursiveFindGenericClasses(typeTag.tpe)
json.readValue[T](entityStream, javaType)
}
which can be used like this:
read[List[Map[Int, SomethingToSerialize]]](inputStream)
Inline version:
<a href="http://yoursite.com/" style="text-decoration:none">yoursite</a>
However remember that you should generally separate the content of your website (which is HTML), from the presentation (which is CSS). Therefore you should generally avoid inline styles.
See John's answer to see equivalent answer using CSS.
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Currently, Robomongo 0.8.x doesn't work with MongoDB 3.0:
For now, don't use Robomongo. For me, the best solution is to use MongoChef.
Got it working with
Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();
<div *ngFor="let celeb of singers">
<p [ngClass]="{
'text-success':celeb.country === 'USA',
'text-secondary':celeb.country === 'Canada',
'text-danger':celeb.country === 'Puorto Rico',
'text-info':celeb.country === 'India'
}">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.
\begin{description}
<YOUR TEXT HERE>
\end{description}
Edit the .htaccess file, so the first line reads 'Test.':
Test.
DirectoryIndex index.php index.html index.htm
...
The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding)
http://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters
says these are RFC 3986 unreserved characters (sec. 2.3) as well as reserved characters (sec 2.2) if they need to retain their special meaning. And also a percent character as part of a percent-encoding.
I had the same problem when trying to run npm
on system emulated in Oracle VirtualBox. I resolved it by adding Google DNS address in Network Adapter properties.
Network Adapter properties > IPv4 properties > Preferred DNS address: 8.8.8.8
.
Under the Links Tab ==> Edit the URL Item ==> Under the URL (Type the Web address)- format the value as follows:
Example: if the URL = http://www.abc.com ==> then suffix the value with ==>
SO, the final value should read as ==> http://www.abc.com#openinnewwindow/,'" target="http://www.abc.com'
DONE ==> this will open the URL in New Window
Gearoid Murphy's solution works better for me since on my distro (Ubuntu 11.10), gcc-4.4 and gcc-4.6 are in the same directory, so --compiler-bindir is no help. The only caveat is I also had to install g++-4.4 and symlink it as well:
sudo ln -s /usr/bin/gcc-4.4 /usr/local/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.4 /usr/local/cuda/bin/g++
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
// this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
// define two types of routes 1. DefaultActionApi and 2. DefaultApi as below
config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });
// decorate the controller action method with [ActionName("Default")] which need to invoked with below url
// http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
// http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
// http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
// http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
// http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller
public class DemoController : ApiController
{
// Mark the method with ActionName attribute (defined in MapRoutes)
[ActionName("Default")]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
}
public HttpResponseMessage GetAll()
{
return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
}
public HttpResponseMessage GetById()
{
return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage DemoGet()
{
return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage CustomGetDetails()
{
return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
}
}
You can also use -S
, -D
or -P
which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:
-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long
This list of shortcuts can be obtained by running the following command:
$ npm help 7 config
This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180
and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
Description is here and this new feature is called Setting With Enlargement.
def addition(a, b): return a + b
def subtraction(a, b): return a - b
def multiplication(a, b): return a * b
def division(a, b): return a / b
keepProgramRunning = True
print "Welcome to the Calculator!"
while keepProgramRunning:
print "Please choose what you'd like to do:"
if you have generic types in your class you should use TypeReference
with convertValue()
.
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
Also you can use that to convert a pojo to java.util.Map
back.
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
Another approach to add the class to element using pure JavaScript
For adding class:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
document.getElementById("div1").classList.remove("classToBeRemoved");
Note: but not supported in IE <= 9 or Safari <=5.0
import javax.persistence.Id;
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
Pros:
Cons:
Competition:
Bottom line: all of our projects are done with Maven for several years already.
You could also do this
#include <comdef.h>
BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
or std::string if you prefer
EDIT: if your original string contains multiple embedded \0 this approach will not work.
Keep multiplying the number after decimal by 2 till it becomes 1.0:
0.25*2 = 0.50
0.50*2 = 1.00
and the result is in reverse order being .01
My computer had the wrong locale set.
I first did
>>> import locale
>>> locale.getpreferredencoding(False)
'ANSI_X3.4-1968'
locale.getpreferredencoding(False)
is the function called by open()
when you don't provide an encoding. The output should be 'UTF-8'
, but in this case it's some variant of ASCII.
Then I ran the bash command locale
and got this output
$ locale
LANG=
LANGUAGE=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=
So, I was using the default Ubuntu locale, which causes Python to open files as ASCII instead of UTF-8. I had to set my locale to en_US.UTF-8
sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
If you can't change the locale system wide, you can invoke all your Python code like this:
PYTHONIOENCODING="UTF-8" python3 ./path/to/your/script.py
or do
export PYTHONIOENCODING="UTF-8"
to set it in the shell you run that in.
I'm confused by one thing: You're planning to create a new naming convention for a new project. Generally you should have a naming convention that is company- or team-wide. If you already have projects that have any form of naming convention, you should not change the convention for a new project. If the convention above is just codification of your existing practices, then you are golden. The more it differs from existing de facto standards the harder it will be to gain mindshare in the new standard.
About the only suggestion I would add is I've taken a liking to _t at the end of types in the style of uint32_t and size_t. It's very C-ish to me although some might complain it's just "reverse" Hungarian.
Try numpy.clip
:
>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
You can clip only the bottom half with clip(0)
.
>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])
You can clip only the top half with clip(max=n)
. (This is much better than my previous suggestion, which involved passing NaN
to the first parameter and using out
to coerce the type.):
>>> a.clip(max=2)
array([ 1, 2, 2, -4, 2])
Another interesting approach is to use where
:
>>> numpy.where(a <= 2, a, 2)
array([ 1, 2, 2, -4, 2])
Finally, consider aix's answer. I prefer clip
for simple operations because it's self-documenting, but his answer is preferable for more complex operations.
Use the DataFrame returned by:
yourDF.orderBy(account)
There is no explicit way to use partitionBy
on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.
I just stumbled upon the same exact issue, with a dataframe that I want to partition by account.
I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions()
etc), right?
I found this very helpful if you are a beginner read this
Update:
In Linux or Unix System there are two places programs send output to: Standard output (stdout) and Standard Error (stderr).You can redirect these output to any file.
Like if you do this ls -a > output.txt
Nothing will be printed in console all output (stdout) is redirected to output file.
And if you try print the content of any file that does not exits means output will be an error like if you print test.txt that not present in current directory
cat test.txt > error.txt
Output will be
cat: test.txt :No such file or directory
But error.txt file will be empty because we redirecting the stdout to a file not stderr.
so we need file descriptor( A file descriptor is nothing more that a positive integer that represents an open file. You can say descriptor is unique id of file) to tell shell which type of output we are sending to file .In Unix /Linux system 1 is for stdout and 2 for stderr.
so now if you do this
ls -a 1> output.txt
means you are sending Standard output (stdout) to output.txt.
and if you do this cat test.txt 2> error.txt
means you are sending Standard Error (stderr) to error.txt .
&1
is used to reference the value of the file descriptor 1 (stdout).
Now to the point 2>&1
means “Redirect the stderr to the same place we are redirecting the stdout”
Now you can do this
cat maybefile.txt > output.txt 2>&1
both Standard output (stdout) and Standard Error (stderr) will redirected to output.txt.
Thanks to Ondrej K. for pointing out
That's because abc
is undefined at the moment of the template rendering. You can use safe navigation operator (?
) to "protect" template until HTTP call is completed:
{{abc?.xyz?.name}}
You can read more about safe navigation operator here.
Update:
Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf
directive to overcome this problem:
<div *ngIf="arr && arr.length > 0">
{{arr[0].name}}
</div>
Read more about NgIf
directive here.
I needed to remove special characters from an XML file. Here's how I did it. char.ToString() is the hero in this code.
string item = "<item type="line" />"
char DC4 = (char)0x14;
string fixed = item.Replace(DC4.ToString(), string.Empty);
You can replace the certificate by just running the certbot again with ./certbot-auto certonly
You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:
-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)
It contains these names: <domain>
You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.
Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------
Just chose Expand
and replace it.
sys.argv[0]
is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]
I have the same problem too, after upgrading win7 to win10. then I check services.msc and found "World Wide Web Publishing Service" was running automatically by default. So then I disabled it, and running the Apache service again.
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
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.
simpler is better - make sense?
in this case just members[0] = 0 works. don't make a simple question so complicated.
You can just use the View.setId(integer)
for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views
you add programmatically.
According to
View
documentationThe identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.
So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.
Credits to this answer.
<video controls width=800 autoplay>
<source src="file path here">
</video>
This will display the video (.mkv) using Google Chrome browser only.
You can use the &
operator. Here is the source code:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10];
int *p;
printf("%p\n", (void *)a);
printf("%p\n", (void *)(&a+1));
printf("---- diff----\n");
printf("%zu\n", sizeof(a[0]));
printf("The size of array a is %zu\n", ((char *)(&a+1)-(char *)a)/(sizeof(a[0])));
return 0;
};
Here is the sample output
1549216672
1549216712
---- diff----
4
The size of array a is 10
Install vim-cool. It was created to fix this specific problem. It turns off highlighting as soon as you move the cursor. Be warned though, it requires a recent vim version!
You can also use DOM to do so. Say you have a function you call like this:
function disable_scroll() {
document.body.style.overflow="hidden";
}
And that's all there is to it! Hope this helps in addition to all the other answers!
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
mentioned also here, you can use this:
import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
To highlight a few points:
The docs recommend using an install environment: https://conda.io/docs/user-guide/install/download.html#choosing-a-version-of-anaconda-or-miniconda
The version archive is here: https://repo.continuum.io/archive/
The version history is here: https://docs.anaconda.com/anaconda/release-notes
"Anaconda3
then its python 3.x and if it is Anaconda2
then its 2.x" - +1 papbiceps
The version archive is sorted newest at the top, but Anaconda2
ABOVE Anaconda3
.
This is your collection
var values = new[] {6, 2, 8, 45, 9, 3, 0};
Make a range of indexes for this collection
var indexes = Enumerable.Range(0, values.Length).ToList();
Use the range to iterate with index
indexes.ForEach(i => values[i] += i);
indexes.ForEach(i => Console.Write("[{0}] = {1}", i, values[i]));
So, this is a code snippet to help better understand this topic.
Printing Tokens
Task: Given a sentence, s, print each word of the sentence in a new line.
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//logic to print the tokens of the sentence.
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
printf("%s\n",p);
}
Input: How is that
Result:
How
is
that
Explanation: So here, "strtok()" function is used and it's iterated using for loop to print the tokens in separate lines.
The function will take parameters as 'string' and 'break-point' and break the string at those break-points and form tokens. Now, those tokens are stored in 'p' and are used further for printing.
I have the following in a types.ts
file for html input, select, and textarea:
export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>
Then import them:
import { InputChangeEventHandler } from '../types'
Then use them:
const updateName: InputChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
Then apply the functions on your markup (replacing ...
with other necessary props):
<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
// ...
</select>
update: please check the answer of Jeff Gilliland below for updated solution
Seems like as this thread says a breaking change was issued:
Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.
Update: can confirm, this was the issue. After downgrading @angular/[email protected]...
to @angular/[email protected]
we could solve this temporarily. Guess we need to update the project for a long term solution.
One of the way to do this is..
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
and another way is to create method which performs task executed by except
block and call it through all of the except
block that you write..
try:
You do your operations here;
......................
except Exception1:
functionname(parameterList)
except Exception2:
functionname(parameterList)
except Exception3:
functionname(parameterList)
else:
If there is no exception then execute this block.
def functionname( parameters ):
//your task..
return [expression]
I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.
For those of you who are using center points and half sizes for their rectangle data, instead of the typical x,y,w,h, or x0,y0,x1,x1, here's how you can do it:
#include <cmath> // for fabsf(float)
struct Rectangle
{
float centerX, centerY, halfWidth, halfHeight;
};
bool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)
{
return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&
(fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight));
}
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
The collation you pick sets whether you are case sensitive or not.
Just for fun:
var mystring = "this,is,a,test"
var newchar = '|'
mystring = mystring.split(',').join(newchar);
Thanks for all Contributions;
that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem
Try nStore, it seems like a nice key/value lightweight dembedded db for node. See https://github.com/creationix/nstore
Be careful in comparing the find result with the the end like for map 'm' as all answer have done above map::iterator i = m.find("f");
if (i == m.end())
{
}
else
{
}
you should not try and perform any operation such as printing the key or value with iterator i if its equal to m.end() else it will lead to segmentation fault.
Make sure you start your application in Debug mode (F5), not without debugging (Ctrl+F5) and then select "Show output from: Debug" in the Output panel in Visual Studio.
If you are pushing a view controller from page view controller page, you cannot update the navigation controller's back button title. To solve this create a delegate back to your parent view controller (you may also be able to traverse the view controller hierarchy back up to the parent).
Furthermore, Back buttons have a character limit. If you exceed that character limit, the system will default to "Back". It will not truncate for you. For example:
backItem.title = "Birthdays/Anniversaries" // Get's converted to "Back".
backItem.title = "Birthdays/Anniversa…" // Fits and shows as is.
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
I found some way to perform in on dictionary contain my custom class methods
foreach (var item in this.Values.Where(p => p.IsActive == false))
item.Refresh();
Where 'this' derived from : Dictionary<string, MyCustomClass>
class MyCustomClass
{
public void Refresh(){}
}
INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';
It's important to understand that your code will sleep for 50 seconds between ending one loop, and starting the next...
A timer will call your loop every 50 seconds, which isn't exactly the same.
They're both valid, but a timer is probably what you're looking for here.
Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-
Assuming you have your NEW empty github or other git repo ready:-
cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master
Alternatively if you have an existing local git repo
cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master
I personally really hate the alternate syntax. One nice thing about the braces is that most IDEs, vim, etc all have bracket highlighting. In my text editor I can double click a brace and it will highlight the whole chunk so I can see where it ends and begins very easily.
I don't know of a single editor that can highlight endif, endforeach, etc.
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
Another possible way to do that:
from django.core.files import File
with open('path_to_file', 'r') as f: # use 'rb' mode for python3
data = File(f)
model.image.save('filename', data, True)
Answers that claim Django model's Meta
and metaclasses are "completely different" are misleading answers.
The construction of Django model class objects, that is to say the object that stands for the class definition itself (yes, classes are also objects), are indeed controlled by a metaclass called ModelBase
, and you can see that code here.
And one of the things that ModelBase
does is to create the _meta
attribute on every Django model which contains validation machinery, field details, save logic and so forth. During this operation, the stuff that is specified in the model's inner Meta
class is read and used within that process.
So, while yes, in a sense Meta
and metaclasses are different 'things', within the mechanics of Django model construction they are intimately related; understanding how they work together will deepen your insight into both at once.
This might be a helpful source of information to better understand how Django models employ metaclasses.
https://code.djangoproject.com/wiki/DevModelCreation
And this might help too if you want to better understand how objects work in general.
Your problem is not actually specific to ejs.
2 things to note here
style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.
In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image
it can be done by
app.use(express.static(__dirname + '/public'));
assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like
<link href="/css/style.css" rel="stylesheet" type="text/css">
Here i assume you have put the css file in css folder inside your public folder.
So folder structure would be
.
./app.js
./public
/css
/style.css
/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g
(123) 456-7890
+(123) 456-7890
+(123)-456-7890
+(123) - 456-7890
+(123) - 456-78-90
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725
This is a very loose option and I prefer to keep it this way, mostly I use it in registration forms where the users need to add their phone number. Usually users have trouble with forms that enforce strict formatting rules, I prefer user to fill in the number and the format it in the display or before saving it to the database. http://regexr.com/3c53v
HttpContext.Current.Session.Remove("sessionname");
it works for me
apt-get install php7.3-mbstring
solved the issue on ubuntu, php version is php-fpm 7.3
Xcode: 6.4 iOS:8 I got this error as well, but for a very different reason.
//UIKeyboardTypeNumberPad needs a "Done" button
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(doneBarButtonTapped:)];
enhancedNumpadToolbar = [[UIToolbar alloc]init]; // previously declared
[self.enhancedNumpadToolbar setItems:@[doneBarButton]];
self.myNumberTextField.inputAccessoryView = self.enhancedNumpadToolbar; //txf previously declared
I got the same error (save mine was "type 4" rather than "type 8"), until I discovered that I was missing this line:
[self.enhancedNumpadToolbar sizeToFit];
I added it, and the sun started shining, the birds resumed chirping, and all was well with the world.
PS You would also get such an error for other mischief, such as forgetting to alloc/init.
One point not getting attention in these answers is that a variable holding a class vs a struct can be a let
while still allowing changes on the object's properties, while you cannot do this with a struct.
This is useful if you don't want the variable to ever point to another object, but still need to modify the object, i.e. in the case of having many instance variables that you wish to update one after another. If it is a struct, you must allow the variable to be reset to another object altogether using var
in order to do this, since a constant value type in Swift properly allows zero mutation, while reference types (classes) don't behave this way.
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
It depends on how you want to use the data in the excel file. If you want to import it into mysql, you could simply save it as a CSV formatted file and then use fgetcsv to parse it.
IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.
Just some examples on usage of array_split
, split
, hsplit
and vsplit
:
n [9]: a = np.random.randint(0,10,[4,4])
In [10]: a
Out[10]:
array([[2, 2, 7, 1],
[5, 0, 3, 1],
[2, 9, 8, 8],
[5, 7, 7, 6]])
Some examples on using array_split
:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'
# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:
[array([[2, 2, 7, 1]]),
array([[5, 0, 3, 1],
[2, 9, 8, 8]]),
array([[5, 7, 7, 6]])]
# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)
Out[5]:
[array([[2],
[5],
[2],
[5]]),
array([[2, 7, 1],
[0, 3, 1],
[9, 8, 8],
[7, 7, 6]])]
An integer as second arg. specifies the number of equal chunks:
In [6]: np.array_split(a, 2, axis=1)
Out[6]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
split
works the same but raises an exception if an equal split is not possible
In addition to array_split
you can use shortcuts vsplit
and hsplit
.
vsplit
and hsplit
are pretty much self-explanatry:
In [11]: np.vsplit(a, 2)
Out[11]:
[array([[2, 2, 7, 1],
[5, 0, 3, 1]]),
array([[2, 9, 8, 8],
[5, 7, 7, 6]])]
In [12]: np.hsplit(a, 2)
Out[12]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
If you have not committed:
git stash
git checkout some-branch
git stash pop
If you have committed and have not changed anything since:
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
If you have committed and then done extra work:
git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop
My problem was caused by the exact opposite of @ehacinom. My Laravel generated API didn't like the trailing '/' on POST requests. Worked fine on localhost but didn't work when uploaded to server.
This has proved to be elusive for me (WebSite Project) until I figured out the following procedure, which combines the solution provided by @Jimmy, with the added step of checking out the solution from Source Control
Steps: (if using VS2013+ with website project and SourceControl)
VWDPort = ......
and change to desired port: (example: "60000" - depends on your IISExpress Settings)Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:
https://pugjs.org/language/iteration.html
Here is one of my snippets: each/for iteration in pug_screenshot
I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).
So in the parent document, add an event listener:
window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
$iframe.height(data);
break;
}
}, false);
And inside the iframe, write a function to post the message:
function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
}
Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:
<body onLoad="resize();">
supposing you have a function:
var fetchPage(page, callback) {
....
request(uri, function (error, response, body) {
....
if (something_good) {
callback(true, page+1);
} else {
callback(false);
}
.....
});
};
you can make use of callbacks like this:
fetchPage(1, x = function(next, page) {
if (next) {
console.log("^^^ CALLBACK --> fetchPage: " + page);
fetchPage(page, x);
}
});
No one suggests threading? Writing the smaller files looks like text book example of where threads are useful. Set up a bunch of threads to create the smaller files. this way, you can create them all in parallel and you don't need to wait for each one to finish. My assumption is that creating the files(disk operation) will take WAY longer than splitting up the data. and of course you should verify first that a sequential approach is not adequate.
String[] value_split = rat_values.split(Pattern.quote("|"));
//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)
String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters)
{
StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
while(StrTkn.hasMoreTokens())
{
ArrLis.add(StrTkn.nextToken());
}
return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 , Service 3 , Atmosphere 3 , Value for money 1 ]
As the question is specifically about alternative tools to get data from PDF as XML so you may be interested to take a look at the commercial tool "ByteScout PDF Extractor SDK" that is capable of doing exactly this: extract text from PDF as XML along with the positioning data (x,y) and font information:
Text in the source PDF:
Products | Units | Price
Output XML:
<row>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="212" y="126" width="47" height="11">Products</text>
</column>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="428" y="126" width="27" height="11">Units</text>
</column>
<column>
<text fontName="Arial" fontSize="11.0" fontStyle="Bold" x="503" y="126" width="26" height="11">Price</text>
</column>
</row>
P.S.: additionally it also breaks the text into a table based structure.
Disclosure: I work for ByteScout
--Drop and Recreate Foreign Key Constraints
SET NOCOUNT ON
DECLARE @table TABLE(
RowId INT PRIMARY KEY IDENTITY(1, 1),
ForeignKeyConstraintName NVARCHAR(200),
ForeignKeyConstraintTableSchema NVARCHAR(200),
ForeignKeyConstraintTableName NVARCHAR(200),
ForeignKeyConstraintColumnName NVARCHAR(200),
PrimaryKeyConstraintName NVARCHAR(200),
PrimaryKeyConstraintTableSchema NVARCHAR(200),
PrimaryKeyConstraintTableName NVARCHAR(200),
PrimaryKeyConstraintColumnName NVARCHAR(200)
)
INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
SELECT
U.CONSTRAINT_NAME,
U.TABLE_SCHEMA,
U.TABLE_NAME,
U.COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
C.CONSTRAINT_TYPE = 'FOREIGN KEY'
UPDATE @table SET
PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME
FROM
@table T
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME
UPDATE @table SET
PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,
PrimaryKeyConstraintTableName = TABLE_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME
UPDATE @table SET
PrimaryKeyConstraintColumnName = COLUMN_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME
--SELECT * FROM @table
--DROP CONSTRAINT:
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
DROP CONSTRAINT ' + ForeignKeyConstraintName + '
GO'
FROM
@table
--ADD CONSTRAINT:
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')
GO'
FROM
@table
GO
I do agree with you, Hamlin. When you are transfer data using SSIS or when want to replicate data, it seems quite necessary to temporarily disable or drop foreign key constraints and then re-enable or recreate them. In these cases, referential integrity is not an issue, because it is already maintained in the source database. Therefore, you can rest assured regarding this matter.
I got the Error even though i was catching the exception.
try {
bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
} catch (IOException e) {
Log.e("blabla", "Error", e);
finish();
}
Issue was that the IOException wasn't imported
import java.io.IOException;
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
- (void)viewDidLoad
{
[self.tableView setSeparatorColor:[UIColor myColor]];
}
I hope that helps - you'll need the self.
to access it, remember.
Swift 4.2
tableView.separatorColor = UIColor.red
Typically you add a class selector to the :not()
pseudo-class like so:
:not(.printable) {
/* Styles */
}
:not([attribute]) {
/* Styles */
}
But if you need better browser support (IE8 and older don't support :not()
), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.
Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable
, or otherwise affect them one way or another. For example, although display
is not inherited, setting display: none
on a :not(.printable)
will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden
instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.
One starting point could be to use this directive (ng-csv) just download the file as csv and that's something excel can understand
http://ngmodules.org/modules/ng-csv
Maybe you can adapt this code (updated link):
http://jsfiddle.net/Sourabh_/5ups6z84/2/
Altough it seems XMLSS (it warns you before opening the file, if you choose to open the file it will open correctly)
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
Make a new batch file (example: openclass.bat) and write this line in the file:
java %~n1
Then place the batch file in, let's say, the system32 folder, go to your Java class file, right click, Properties, Open with..., then find your batch file, select it and that's that...
It works for me.
PS: I can't find a way to close the cmd window when I close the Java class. For now...
More simple,
echo $line | sed 's/\s/\n/g'
\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]
\n --> new line
Including the fb:app_id
tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.
The fb:admins
tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.
You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins
is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.
fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>
and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.