You Can use just finish();
everywhere after Activity Start for clear that Activity from Stack.
That's known as an Arrow Function, part of the ECMAScript 2015 spec...
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(f => f.length);_x000D_
_x000D_
console.log(bar); // 1,2,3
_x000D_
Shorter syntax than the previous:
// < ES6:_x000D_
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(function(f) {_x000D_
return f.length;_x000D_
});_x000D_
console.log(bar); // 1,2,3
_x000D_
The other awesome thing is lexical this
... Usually, you'd do something like:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
var self = this;_x000D_
setInterval(function() {_x000D_
// this is the Window, not Foo {}, as you might expect_x000D_
console.log(this); // [object Window]_x000D_
// that's why we reassign this to self before setInterval()_x000D_
console.log(self.count);_x000D_
self.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
But that could be rewritten with the arrow like this:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
setInterval(() => {_x000D_
console.log(this); // [object Object]_x000D_
console.log(this.count); // 1, 2, 3_x000D_
this.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
For more, here's a pretty good answer for when to use arrow functions.
I found that you can get this error if the returned object has getter only auto properties that are initialized in the constructor (with C# 6.0 syntax).
I believe this is due to WCF deserializing objects on the client side using a parameter-less constructor then setting the properties on the object. It needs to have a set
available (it can be private) to fill the object, otherwise it'll fail.
<input attr1='a' attr2='b' attr3='c'>foo</input>
getAttribute(attr1)
you get 'a'
getAttribute(attr2)
you get 'b'
getAttribute(attr3)
you get 'c'
getText()
with no parameter you can only get 'foo'
To expand on my comment.
You can validate on the command line using php -l [filename]
, which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.
Here's an example of the output when run on a file containing:
<?php
echo no quotes or semicolon
Results in:
PHP Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Errors parsing badfile.php
I suggested you build your own validator.
A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l
and echos the output.
Note: this is not a security risk it does not execute the file, just checks for syntax errors.
Here's a really basic example of creating your own:
<?php
if (isset($_FILES['file'])) {
echo '<pre>';
passthru('php -l '.$_FILES['file']['tmp_name']);
echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
Here's another way to do for multiple Button
(In this case ImageView
)
MainActivity.java
findViewById(R.id.arrowIV).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (strokeWidthIV.getAlpha() == 0f) {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(-120 * 4).alpha(1f);
findViewById(R.id.colorChooseIV).animate().translationXBy(-120 * 3).alpha(1f);
findViewById(R.id.saveIV).animate().translationXBy(-120 * 2).alpha(1f);
findViewById(R.id.clearAllIV).animate().translationXBy(-120).alpha(1f);
} else {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(120 * 4).alpha(0f);
findViewById(R.id.colorChooseIV).animate().translationXBy(120 * 3).alpha(0f);
findViewById(R.id.saveIV).animate().translationXBy(120 * 2).alpha(0f);
findViewById(R.id.clearAllIV).animate().translationXBy(120).alpha(0f);
}
}
});
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<ImageView
android:id="@+id/strokeWidthIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_edit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/colorChooseIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_palette"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/saveIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/clearAllIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_clear_all"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/arrowIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:contentDescription="Arrow"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_arrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.
Valid numbers for ports are: 0 to 2^16-1 = 0 to 65535
That is because a port number is 16 bit length.
However ports are divided into:
Well-known ports: 0 to 1023 (used for system services e.g. HTTP, FTP, SSH, DHCP ...)
Registered/user ports: 1024 to 49151 (you can use it for your server, but be careful some famous applications: like Microsoft SQL Server database management system (MSSQL) server or Apache Derby Network Server are already taking from this range i.e. it is not recommended to assign the port of MSSQL to your server otherwise if MSSQL is running then your server most probably will not run because of port conflict )
Dynamic/private ports: 49152 to 65535. (not used for the servers rather the clients e.g. in NATing service)
In programming you can use any numbers 0 to 65535 for your server, however you should stick to the ranges mentioned above, otherwise some system services or some applications will not run because of port conflict.
Check the list of most ports here: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
You can reference is that way if you wrap the query, like this:
SELECT P
FROM (SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts) innertable
WHERE P LIKE 'NW101%'
Be sure to give the wrapped select an alias, even unused (SQL Server doesn't allow it without one IIRC)
You don't need a regex for this one. Use the isNAN()
JavaScript function.
The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.
if (isNaN($('#Field').val()) == false) {
// It's a number
}
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):
SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
INTO v_sql
FROM transaction_log;
EXECUTE IMMEDIATE v_sql;
Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.
One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.
The .git
at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git
. The git client and protocol honours this convention by testing for project.git
when only project
is specified.
git://[email protected]/peter/first_app.git
is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git
is the ssh
url mentioned on that page.
git
is flexible. It allows you to track your local branch against almost any branch of any repository. While master
(your local default branch) tracking origin/master
(the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push
is so verbose. It tells git what to do with the local master
branch when you do a git pull
or a git push
.
The default for git push
and git pull
is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.
git
is fairly elegant and comprehensible but there is a learning curve to walk through.
I hope you have found a good solution. I had the same problem, and the way I worked around it is probably not the best but it is working now.
it involves creating a linked server and using dynamic sql - not the best, but if anyone can suggest something better, please comment/answer.
declare @sql nvarchar(max)
DECLARE @DB_SPACE TABLE (
[DatabaseName] NVARCHAR(128) NOT NULL,
[FILEID] [smallint] NOT NULL,
[FILE_SIZE_MB] INT NOT NULL DEFAULT (0),
[SPACE_USED_MB] INT NULL DEFAULT (0),
[FREE_SPACE_MB] INT NULL DEFAULT (0),
[LOGICALNAME] SYSNAME NOT NULL,
[DRIVE] NCHAR(1) NOT NULL,
[FILENAME] NVARCHAR(260) NOT NULL,
[FILE_TYPE] NVARCHAR(260) NOT NULL,
[THE_AUTOGROWTH_IN_KB] INT NOT NULL DEFAULT(0)
,filegroup VARCHAR(128)
,maxsize VARCHAR(25)
PRIMARY KEY CLUSTERED ([DatabaseName] ,[FILEID] )
)
SELECT @SQL ='SELECT [DatabaseName],
[FILEID],
[FILE_SIZE_MB],
[SPACE_USED_MB],
[FREE_SPACE_MB],
[LOGICALNAME],
[DRIVE],
[FILENAME],
[FILE_TYPE],
[THE_AUTOGROWTH_IN_KB]
,filegroup
,maxsize FROM OPENQUERY('+ QUOTENAME('THE_MONITOR') + ','''+ ' EXEC MASTER.DBO.monitoring_database_details ' +''')'
exec sp_executesql @sql
INSERT INTO @DB_SPACE(
[DatabaseName],
[FILEID],
[FILE_SIZE_MB],
[SPACE_USED_MB],
[FREE_SPACE_MB],
[LOGICALNAME],
[DRIVE],
[FILENAME],
[FILE_TYPE],
THE_AUTOGROWTH_IN_KB,
[filegroup],
maxsize
)
EXEC SP_EXECUTESQL @SQL
this is working for me now. I can guarantee the number of columns and type of columns returned by the stored procedure are the same as in this table, simply because I return the same table from the stored procedure.
thanks and regards marcelo
Use timedelta to switch between timezones. All you need is the offset in hours between timezones. Don't have to fiddle with boundaries for all 6 elements of a datetime object. timedelta handles leap years, leap centuries, etc., too, with ease. You must first
from datetime import datetime, timedelta
Then if offset
is the timezone delta in hours:
timeout = timein + timedelta(hours = offset)
where timein and timeout are datetime objects. e.g.
timein + timedelta(hours = -8)
converts from GMT to PST.
So, how to determine offset
? Here is a simple function provided you only have a few possibilities for conversion without using datetime objects that are timezone "aware" which some other answers nicely do. A bit manual, but sometimes clarity is best.
def change_timezone(timein, timezone, timezone_out):
'''
changes timezone between predefined timezone offsets to GMT
timein - datetime object
timezone - 'PST', 'PDT', 'GMT' (can add more as needed)
timezone_out - 'PST', 'PDT', 'GMT' (can add more as needed)
'''
# simple table lookup
tz_offset = {'PST': {'GMT': 8, 'PDT': 1, 'PST': 0}, \
'GMT': {'PST': -8, 'PDT': -7, 'GMT': 0}, \
'PDT': {'GMT': 7, 'PST': -1, 'PDT': 0}}
try:
offset = tz_offset[timezone][timezone_out]
except:
msg = 'Input timezone=' + timezone + ' OR output time zone=' + \
timezone_out + ' not recognized'
raise DateTimeError(msg)
return timein + timedelta(hours = offset)
After looking at the numerous answers and playing around with the tightest code I can think of (for now) it seems best that all applications, where time is important and mixed timezones must be accounted for, should make a real effort to make all datetime objects "aware". Then it would seem the simplest answer is:
timeout = timein.astimezone(pytz.timezone("GMT"))
to convert to GMT for example. Of course, to convert to/from any other timezone you wish, local or otherwise, just use the appropriate timezone string that pytz understands (from pytz.all_timezones). Daylight savings time is then also taken into account.
You can get all keys in the Request.Form and then compare and get your desired values.
Your method body will look like this: -
List<int> listValues = new List<int>();
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("List"))
{
listValues.Add(Convert.ToInt32(Request.Form[key]));
}
}
Here is the very nice link which explains the storage of signed and unsigned INT in C -
http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O
Taken from this above article -
"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."
I liked Addison Klinke's post the most, as being the simplest, but used Wojciech Moszczynsk’s suggestion for filtering and charting, but extended the filter to avoid absolute values, so given a large correlation matrix, filter it, chart it, and then flatten it:
Created, Filtered and Charted
dfCorr = df.corr()
filteredDf = dfCorr[((dfCorr >= .5) | (dfCorr <= -.5)) & (dfCorr !=1.000)]
plt.figure(figsize=(30,10))
sn.heatmap(filteredDf, annot=True, cmap="Reds")
plt.show()
Function
In the end, I created a small function to create the correlation matrix, filter it, and then flatten it. As an idea, it could easily be extended, e.g., asymmetric upper and lower bounds, etc.
def corrFilter(x: pd.DataFrame, bound: float):
xCorr = x.corr()
xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
xFlattened = xFiltered.unstack().sort_values().drop_duplicates()
return xFlattened
corrFilter(df, .7)
Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).
Or just use this in your View(Razor page)
@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))
I recommend that don't add date format in your model class
opacity: 0.99; on wrapper solve webkit bug
This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
output
Also, You can check out my GitHub code
If you want to match anything after a word stop an not only at the start of the line you may use : \bstop.*\b
- word followed by line
Or if you want to match the word in the string use \bstop[a-zA-Z]*
- only the words starting with stop
Or the start of lines with stop ^stop[a-zA-Z]*
for the word only - first word only
The whole line ^stop.*
- first line of the string only
And if you want to match every string starting with stop including newlines use : /^stop.*/s
- multiline string starting with stop
You can also execute javascript using webdriver.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
driver.execute_script('document.title')
or store the value in a variable
result = driver.execute_script('var text = document.title ; return var')
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
Use mutple backgorund on the element, and use a linear-gradient as your color overlay by declaring both start and end color-stops as the same value.
Note that layers in a multi-background declaration are read much like they are rendered, top-to-bottom, so put your overlay first, then your bg image:
#header {
background:
linear-gradient(to bottom, rgba(100, 100, 0, 0.5), rgba(100, 100, 0, 0.5)) cover,
url(../img/bg.jpg) 0 0 no-repeat fixed;
height: 100%;
overflow: hidden;
color: #FFFFFF
}
For Windows Users:
If the python
command is not in your $PATH
environment var.
Open PowerShell and run these commands to find the folder
cd \
ls *ython* -Recurse -Directory
That should tell you where python is installed
This usually occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL
, there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Data folder
. Thats it . Now start the MS SQL service and you are done
document.getElementById("").readOnly = true
If I properly understood your question, supposing your running script is
/relative/path/to/script/index.php
This would give you the parent directory of your running script relative to the document www:
$parent_dir = dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/';
//$parent_dir will be '/relative/path/to/'
If you want the parent directory of your running script relative to server root:
$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/';
//$parent_dir will be '/root/some/path/relative/path/to/'
Just add this code to your image css
body{
background:
/* top, transparent black, faked with gradient */
linear-gradient(
rgba(0, 0, 0, 0.7),
rgba(0, 0, 0, 0.7)
),
/* bottom, image */
url(https://images.unsplash.com/photo-1614030424754-24d0eebd46b2);
}
_x000D_
Reference: linear-gradient() - CSS | MDN
UPDATE: Not all browsers support RGBa, so you should have a 'fallback color'. This color will be most likely be solid (fully opaque) ex:background:rgb(96, 96, 96)
. Refer to this blog for RGBa browser support.
You can override values in php.ini from your PHP code using ini_set()
.
$content = '';
for($rowth=0; $rowth<=100; $rowth++){
$content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
//$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
$content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";
}
For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:
While the browser is open, press F12 to access Web Developer tools
When opened, click the "Network" option
Initially, it is possible the page data is not present/up to date. Refresh the page if necessary
Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)
The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
Moment.subtract
does not support an argument of type Moment - documentation:
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
The simplest solution is to specify the time delta as an object:
// Assumes string is hh:mm:ss
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"
If you already installed in your eclipse you can solve this problem below,
Go to Windows -> Install New Software and find your android plugin address
Check all lists and re-install your android plugin for eclipse
I solved it like this
Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.
Please see the below example code for Windows IIS Servers with Web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="1024" maxUrl="2048">
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
This would also work on a server level using machine.config.
Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.
Using an enhanced for would be even nicer:
int sum = 0;
for (int d : data) sum += d;
Another thing that will probably give you a big surprise is the wrong result that you will obtain from
double average = sum / data.length;
Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length
and only then promote that integer to a double
. A solution would be
double average = 1.0d * sum / data.length;
This will force the dividend into a double
, which will automatically propagate to the divisor.
I would use
like 'Express Edition%'
Example:
DECLARE @edition varchar(50);
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)
DECLARE @isExpress bit
if @edition like 'Express Edition%'
set @isExpress = 1;
else
set @isExpress = 0;
print @isExpress
Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0
npm install --save-dev @angular-devkit/build-angular
or,
yarn add @angular-devkit/build-angular --dev
First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).
If your data is not large, you can do
SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'
using OR
if you have multiple keywords.
You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace
public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
public ProducerConsumerQueue()
: base(new ConcurrentQueue<T>())
{
}
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
/// <param name="maxSize"></param>
public ProducerConsumerQueue(int maxSize)
: base(new ConcurrentQueue<T>(), maxSize)
{
}
}
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
strsplit(c('a|b','b|c'),'|',fixed=TRUE)
In my case, IntelliJ didn't compile the test sources for a strange reason. I simply modified the build configuration and added the maven goal clean test-compile
in the Before launch
section
String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'????? ?????',
'????? ?????????',
'????? ?? ???'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'???',
'?????? ????',
'?????? ????',
'?????',
'????? ??? ?????',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.
print(*3*('-',), sep='_')
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount()
function has to be used.
Let's see why
Before using PDO I just simply used
mysql_num_rows()
.
Means you already did it wrong. Using mysql_num_rows()
or rowCount()
to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*)
query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll()
.
fetchAll()
is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount()
nor fetchAll()
.
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll()
. Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT
, WHERE
or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll()
. And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount()
won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
In Mercurial you use hg log --keyword
to search for keywords in the commit messages and hg log --user
to search for a particular user. See hg help log
for other ways to limit the log.
Yes, the problem is that there are no commits in "bare". This is a problem with the first commit only, if you create the repos in the order (bare,alice). Try doing:
git push --set-upstream origin master
This would only be required the first time. Afterwards it should work normally.
As Chris Johnsen pointed out, you would not have this problem if your push.default was customized. I like upstream/tracking.
i know this is an old post but there is an option to sent the elemd id with the function call:
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
function f1(objButton)
{
if (objButton.innerHTML=="EXPAND") objButton.innerHTML = "MINIMIZE";
else objButton.innerHTML = "EXPAND";
}
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
In Python 2.7 with iPython:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
A hidden attribute is a boolean attribute (True/False). When this attribute is used on an element, it removes all relevance to that element. When a user views the html page, elements with the hidden attribute should not be visible.
Example:
<p hidden>You can't see this</p>
Aria-hidden attributes indicate that the element and ALL of its descendants are still visible in the browser, but will be invisible to accessibility tools, such as screen readers.
Example:
<p aria-hidden="true">You can't see this</p>
Take a look at this. It should answer all your questions.
Note: ARIA stands for Accessible Rich Internet Applications
Sources: Paciello Group
ASP.NET Core (in my case 3.1) provides us with Constructor injections into Controllers, so you may simply add following constructor:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IConfiguration m_config;
public TestController(IConfiguration config)
{
m_config = config;
}
[HttpGet]
public string Get()
{
//you can get connection string as follows
string connectionString = m_config.GetConnectionString("Default")
}
}
Here what appsettings.json may look like:
{
"ConnectionStrings": {
"Default": "YOUR_CONNECTION_STRING"
}
}
I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:
subinacl.exe /service w3svc /grant=VMX001\job=PTO
The permissions you can grant are defined as follows (list taken from here):
F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service
U : Service User-Defined Control Commands
So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
You can implement this functionality like this
Firstly, using the ls command pointed to the targeted directory. Later using find command filter the result from it.
From your case, it sounds like - always the filename starts with a word
file***.txt
ls /some/path/here | find . -name 'file*.txt' (* represents some wild card search)
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
A REGEXP_LIKE
will do a case-insensitive regexp search.
select * from Users where Regexp_Like (User_Name, 'karl|anders|leif','i')
This will be executed as a full table scan - just as the LIKE or
solution, so the performance will be really bad if the table is not small. If it's not used often at all, it might be ok.
If you need some kind of performance, you will need Oracle Text (or some external indexer).
To get substring indexing with Oracle Text you will need a CONTEXT index. It's a bit involved as it's made for indexing large documents and text using a lot of smarts. If you have particular needs, such as substring searches in numbers and all words (including "the" "an" "a", spaces, etc) , you need to create custom lexers to remove some of the smart stuff...
If you insert a lot of data, Oracle Text will not make things faster, especially if you need the index to be updated within the transactions and not periodically.
anyway you have not a unlimited accuracy so C define a constant in this way:
#define PI 3.14159265358979323846
import math.h to use this
Label12.Text = "My ID : " + System.Net.Dns.GetHostByName(Net.Dns.GetHostName()).AddressList(0).ToString()
use this code, without any variable
I would do
StartDate1.IsBetween(StartDate2, EndDate2) || EndDate1.IsBetween(StartDate2, EndDate2)
Where IsBetween
is something like
public static bool IsBetween(this DateTime value, DateTime left, DateTime right) {
return (value > left && value < right) || (value < left && value > right);
}
mode con:cols=[whatever you want] lines=[whatever you want].
The unit is the number of characters that fit in the command prompt, eg.
mode con:cols=80 lines=100
will make the command prompt 80 ASCII chars of width and 100 of height
May not be directly related to browsers but fiddler is another good software.
I solved this error using the bellow i get it from here
ionic cordova run browser
will load those native plugins that support browser
platform.
os.homedir()
was added by this PR and is part of the public 4.0.0 release of nodejs.
Example usage:
const os = require('os');
console.log(os.homedir());
There's another way by setting the OS variable, SPRING_PROFILES_ACTIVE.
for eg :
SPRING_PROFILES_ACTIVE=dev gradle clean bootRun
Reference : How to set active Spring profiles
There are a lot of ways to reverse a string but I also created another one just for fun. I think this approach is not that bad.
def reverse(_str):
list_char = list(_str) # Create a hypothetical list. because string is immutable
for i in range(len(list_char)/2): # just t(n/2) to reverse a big string
list_char[i], list_char[-i - 1] = list_char[-i - 1], list_char[i]
return ''.join(list_char)
print(reverse("Ehsan"))
If your Main
class is in a package called FileManagement
, then try:
java -cp . FileManagement.Main
in the parent folder of the FileManagement
folder.
If your Main
class is not in a package (the default package) then cd to the FileManagement
folder and try:
java -cp . Main
More info about the CLASSPATH and how the JRE find classes:
This code snippet:
int& func1()
{
int i;
i = 1;
return i;
}
will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1()
returns, int i
dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.
int main()
{
int& p = func1();
/* p is garbage */
}
The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for delete
ing the allocated int
.
int* func2()
{
int* p;
p = new int;
*p = 1;
return p;
}
int main()
{
int* p = func2();
/* pointee still exists */
delete p; // get rid of it
}
Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete
it yourself.
In either case, you can just return the value itself (although I realize the example you provided was probably contrived):
int func3()
{
return 1;
}
int main()
{
int v = func3();
// do whatever you want with the returned value
}
Note that it's perfectly fine to return big objects the same way func3()
returns primitive values because just about every compiler nowadays implements some form of return value optimization:
class big_object
{
public:
big_object(/* constructor arguments */);
~big_object();
big_object(const big_object& rhs);
big_object& operator=(const big_object& rhs);
/* public methods */
private:
/* data members */
};
big_object func4()
{
return big_object(/* constructor arguments */);
}
int main()
{
// no copy is actually made, if your compiler supports RVO
big_object o = func4();
}
Interestingly, binding a temporary to a const reference is perfectly legal C++.
int main()
{
// This works! The returned temporary will last as long as the reference exists
const big_object& o = func4();
// This does *not* work! It's not legal C++ because reference is not const.
// big_object& o = func4();
}
In my case (.NET Core 3.0) I had to configure JSON serialization to resolve camelCase properties using AddNewtonsoftJson():
services.AddMvc(options =>
{
// (Irrelevant for the answer)
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Do this in your Startup / Dependency Injection setup.
Your sklearn version is too low, model_selection
is imported by 0.18.1, so please update the sklearn version.
You can use .filter() or .find(). One difference that filter
will iterate over all items and returns any which passes the condition as array while find
will return the first matched item and break the iteration.
Example
var questions = [_x000D_
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},_x000D_
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
Make sure to download these from here:
Also create PATH
enviroment variable on you computer like this (if it doesn't exist already):
PATH
variable doesn't exist among "User variables" click New
(Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin;
<-- please check out the right version, this may differ as Oracle keeps updating Java). ;
in the end enables assignment of multiple values to PATH
variable.To be sure that everything works, open CMD Prompt and type: java -version
to check for Java version and javac
to be sure that compiler responds.
I hope this helps. Good luck!
It is possible to include JavaScript in your code and still support non-JavaScript users.
If a user clicks any of the following links without JavaScript enabled, it will simply open a new tab:
<!-- Remember to change URL_HERE, TITLE_HERE and TWITTER_HANDLE_HERE -->
<a href="http://www.facebook.com/sharer/sharer.php?u=URL_HERE&t=TITLE_HERE" target="_blank" class="share-popup">Share on Facebook</a>
<a href="http://www.twitter.com/intent/tweet?url=URL_HERE&via=TWITTER_HANDLE_HERE&text=TITLE_HERE" target="_blank" class="share-popup">Share on Twitter</a>
<a href="http://plus.google.com/share?url=URL_HERE" target="_blank" class="share-popup">Share on Googleplus</a>
Because they contain the share-popup
class, we can easily reference these in jQuery, and change the window size to suit the domain we are sharing from:
$(".share-popup").click(function(){ var window_size = "width=585,height=511"; var url = this.href; var domain = url.split("/")[2]; switch(domain) { case "www.facebook.com": window_size = "width=585,height=368"; break; case "www.twitter.com": window_size = "width=585,height=261"; break; case "plus.google.com": window_size = "width=517,height=511"; break; } window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' + window_size); return false; });
No more ugly inline JavaScript, or countless window sizing alterations. And it still supports non-JavaScript users.
Assuming your div
has an id="myDiv"
, add the following to your CSS. The cursor: pointer
specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):
CSS to Add
#myDiv
{
cursor: pointer;
}
You can simply add the cursor style to your div
's HTML like this:
<div style="cursor: pointer">
</div>
EDIT:
If you are determined to use jQuery for this, then add the following line to your $(document).ready()
or body onload
: (replace myClass
with whatever class all of your div
s share)
$('.myClass').css('cursor', 'pointer');
You could use the ViewCommand design pattern. It describes a method for the MVVM design pattern to control a View from a ViewModel with commands.
I've implemented it based on King A.Majid's suggestion to use the MVVM Light Messenger class. The ViewCommandManager class handles invoking commands in connected views. It's basically the other direction of regular Commands, for these cases when a ViewModel needs to do some action in its View. It uses reflection like data-bound commands and WeakReferences to avoid memory leaks.
http://dev.unclassified.de/source/viewcommand (also published on CodeProject)
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)}
and I got errors, but when I change my code to exec sp...
it works very well.
I post my code in hope this helps others with problems like mine:
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
cs.setEscapeProcessing(true);
cs.setQueryTimeout(90);
cs.setString(1, "valueA");
cs.setString(2, "valueB");
cs.setString(3, "0418");
//commented, because no need to register parameters out!, I got results from the resultset.
//cs.registerOutParameter(1, Types.VARCHAR);
//cs.registerOutParameter(2, Types.VARCHAR);
rs = cs.executeQuery();
ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
while (rs.next()) {
ObjectX to = new ObjectX();
to.setFecha(rs.getString(1));
to.setRefId(rs.getString(2));
to.setRefNombre(rs.getString(3));
to.setUrl(rs.getString(4));
listaObjectX.add(to);
}
return listaObjectX;
} catch (SQLException se) {
System.out.println("Error al ejecutar SQL"+ se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
You could also achieve this with the parse_date_time
or fast_strptime
functions from the lubridate
-package:
> parse_date_time(dates1, "ym")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
> fast_strptime(dates1, "%Y-%m")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
The difference between those two is that parse_date_time
allows for lubridate-style format specification, while fast_strptime
requires the same format specification as strptime
.
For specifying the timezone, you can use the tz
-parameter:
> parse_date_time(dates1, "ym", tz = "CET")
[1] "2009-01-01 CET" "2009-02-01 CET" "2009-03-01 CET"
When you have irregularities in your date-time data, you can use the truncated
-parameter to specify how many irregularities are allowed:
> parse_date_time(dates2, "ymdHMS", truncated = 3)
[1] "2012-06-01 12:23:00 UTC" "2012-06-01 12:00:00 UTC" "2012-06-01 00:00:00 UTC"
Used data:
dates1 <- c("2009-01","2009-02","2009-03")
dates2 <- c("2012-06-01 12:23","2012-06-01 12",'2012-06-01")
For Spark 2.1.0, my suggestion would be to use head(n: Int)
or take(n: Int)
with isEmpty
, whichever one has the clearest intent to you.
df.head(1).isEmpty
df.take(1).isEmpty
with Python equivalent:
len(df.head(1)) == 0 # or bool(df.head(1))
len(df.take(1)) == 0 # or bool(df.take(1))
Using df.first()
and df.head()
will both return the java.util.NoSuchElementException
if the DataFrame is empty. first()
calls head()
directly, which calls head(1).head
.
def first(): T = head()
def head(): T = head(1).head
head(1)
returns an Array, so taking head
on that Array causes the java.util.NoSuchElementException
when the DataFrame is empty.
def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)
So instead of calling head()
, use head(1)
directly to get the array and then you can use isEmpty
.
take(n)
is also equivalent to head(n)
...
def take(n: Int): Array[T] = head(n)
And limit(1).collect()
is equivalent to head(1)
(notice limit(n).queryExecution
in the head(n: Int)
method), so the following are all equivalent, at least from what I can tell, and you won't have to catch a java.util.NoSuchElementException
exception when the DataFrame is empty.
df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty
I know this is an older question so hopefully it will help someone using a newer version of Spark.
You can initialize it just like any list:
public List<ContactNumber> ContactNumbers { get; set; }
public Human(int id)
{
Id = id;
ContactNumbers = new List<ContactNumber>();
}
public Human(int id, string address, string name) :this(id)
{
Address = address;
Name = name;
// no need to initialize the list here since you're
// already calling the single parameter constructor
}
However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:
public List<ContactNumber> ContactNumbers { get; private set; }
I use this, if you want only one view to be bring to front when needed:
containerView.bringChildToFront(topView);
containerView is container of views to be sorted, topView is view which i want to have as top most in container.
for multiple views to arrange is about to use setChildrenDrawingOrderEnabled(true) and overriding getChildDrawingOrder(int childCount, int i) as mentioned above.
By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.
To disable this, use: struct.unpack("=BH", data)
. This will use standard alignment, which doesn't add padding:
>>> struct.calcsize('=BH')
3
The =
character will use native byte ordering. You can also use <
or >
instead of =
to force little-endian or big-endian byte ordering, respectively.
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
if the value is 0 then it wasn't successful, but if 1 then successful.
$this->db->affected_rows();
This function normalizes down all whitespace, including line breaks, to single spaces. Not exactly what the original question asked for, but likely to do exactly what is needed in many cases:
import org.apache.commons.lang3.StringUtils;
final String cleansedString = StringUtils.normalizeSpace(rawString);
<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>
<input type="submit" id="btn_submit" value="click me"/>
<script>
$('#btn_submit').on('click',function(){
$('#ddlvalue').val(0);
});
</script>
If ESLint is running in the terminal but not inside VSCode, it is probably
because the extension is unable to detect both the local and the global
node_modules
folders.
To verify, press Ctrl+Shift+U in VSCode to open
the Output
panel after opening a JavaScript file with a known eslint
issue.
If it shows Failed to load the ESLint library for the document {documentName}.js
-or- if the Problems
tab shows an error or a warning that
refers to eslint
, then VSCode is having a problem trying to detect the path.
If yes, then set it manually by configuring the eslint.nodePath
in the VSCode
settings (settings.json
). Give it the full path (for example, like
"eslint.nodePath": "C:\\Program Files\\nodejs",
) -- using environment variables
is currently not supported.
This option has been documented at the ESLint extension page.
Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}
I've found with 1.5 components that abstracting the styling from the DOM to work best in my async situation.
Example:
<div ng-style="{ 'background': $ctrl.backgroundUrl }"></div>
And in the controller, something likes this:
this.$onChanges = onChanges;
function onChanges(changes) {
if (changes.value.currentValue){
$ctrl.backgroundUrl = setBackgroundUrl(changes.value.currentValue);
}
}
function setBackgroundUrl(value){
return 'url(' + value.imgUrl + ')';
}
go to your project dir and type:
git filter-branch --tree-filter 'rm -f <deleted-file>' HEAD
after that push --force for delete file from all commits.
git push origin --force --all
var d = new Date(); // calling the function formatDate(d,4); function formatDate(dateObj,format) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var curr_date = dateObj.getDate(); var curr_month = dateObj.getMonth(); curr_month = curr_month + 1; var curr_year = dateObj.getFullYear(); var curr_min = dateObj.getMinutes(); var curr_hr= dateObj.getHours(); var curr_sc= dateObj.getSeconds(); if(curr_month.toString().length == 1) curr_month = '0' + curr_month; if(curr_date.toString().length == 1) curr_date = '0' + curr_date; if(curr_hr.toString().length == 1) curr_hr = '0' + curr_hr; if(curr_min.toString().length == 1) curr_min = '0' + curr_min; if(format ==1)//dd-mm-yyyy { return curr_date + "-"+curr_month+ "-"+curr_year; } else if(format ==2)//yyyy-mm-dd { return curr_year + "-"+curr_month+ "-"+curr_date; } else if(format ==3)//dd/mm/yyyy { return curr_date + "/"+curr_month+ "/"+curr_year; } else if(format ==4)// MM/dd/yyyy HH:mm:ss { return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc; } }
It's a standard, ordinary SOAP web service. SSH has nothing to do here. I just called it with curl (one-liner):
$ curl -X POST -H "Content-Type: text/xml" \
-H 'SOAPAction: "http://api.eyeblaster.com/IAuthenticationService/ClientLogin"' \
--data-binary @request.xml \
https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc
Where request.xml
file has the following contents:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.eyeblaster.com/">
<soapenv:Header/>
<soapenv:Body>
<api:ClientLogin>
<api:username>user</api:username>
<api:password>password</api:password>
<api:applicationKey>key</api:applicationKey>
</api:ClientLogin>
</soapenv:Body>
</soapenv:Envelope>
I get this beautiful 500:
<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<s:Fault>
<faultcode>s:Security.Authentication.UserPassIncorrect</faultcode>
<faultstring xml:lang="en-US">The username, password or application key is incorrect.</faultstring>
</s:Fault>
</s:Body>
</s:Envelope>
Have you tried soapui?
Mock data:
df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]
Group Apple Orange
0 A 0.465636 0.537723
1 A 0.560537 0.727238
2 A 0.268154 0.648927
3 B 0.722644 0.115550
4 C 0.586346 0.042896
5 B 0.562881 0.369686
6 B 0.395236 0.672477
7 C 0.577949 0.358801
8 A 0.764069 0.642724
9 C 0.731076 0.302369
You can use the Seaborn library for these plots. First melt
the dataframe to format data and then create the boxplot of your choice.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')
ASP.Net automatically generates unique client IDs for server-side controls.
Change it to
$('#<%= lblVessel.ClientID %>')
In ASP.Net 4.0, you could also set the ClientIDMode
property to Static
instead.
As to the CSS suggestion:
#myCanvas {
width: 100%;
height: 100%;
}
By the standard, CSS does not size the canvas coordinate system, it scales the content. In Chrome, the CSS mentioned will scale the canvas up or down to fit the browser's layout. In the typical case where the coordinate system is smaller than the browser's dimensions in pixels, this effectively lowers the resolution of your drawing. It most likely results in non-proportional drawing as well.
Short and concise answer for Swift 3:
guard let requestUrl = URL(string: yourURL) else { return }
let request = URLRequest(url:requestUrl)
URLSession.shared.dataTask(with: request) {
(data, response, error) in
...
}.resume()
There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:
cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;
Output is:
123
123 123
You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the
'this gives you an excel app
oExcel = CreateObject("Excel.Application")
'this opens a work book of your choice, just set "Target" to a filepath
oBook = oExcel.Workbooks.Open(Target)
'how to read
set readVar = oExcel.Cell(1,1).value
'how to write
oExcel.Cell(1,2).value = writeVar
'Saves & Closes Book then ends excel
oBook.Save
oBook.Close
oExcel.Quit
sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
(4castle's answer is better than the below if you can assume Java >= 9)
You need to create a matcher and use that to iteratively find matches.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("your regular expression here")
.matcher(yourStringHere);
while (m.find()) {
allMatches.add(m.group());
}
After this, allMatches
contains the matches, and you can use allMatches.toArray(new String[0])
to get an array if you really need one.
You can also use MatchResult
to write helper functions to loop over matches
since Matcher.toMatchResult()
returns a snapshot of the current group state.
For example you can write a lazy iterator to let you do
for (MatchResult match : allMatches(pattern, input)) {
// Use match, and maybe break without doing the work to find all possible matches.
}
by doing something like this:
public static Iterable<MatchResult> allMatches(
final Pattern p, final CharSequence input) {
return new Iterable<MatchResult>() {
public Iterator<MatchResult> iterator() {
return new Iterator<MatchResult>() {
// Use a matcher internally.
final Matcher matcher = p.matcher(input);
// Keep a match around that supports any interleaving of hasNext/next calls.
MatchResult pending;
public boolean hasNext() {
// Lazily fill pending, and avoid calling find() multiple times if the
// clients call hasNext() repeatedly before sampling via next().
if (pending == null && matcher.find()) {
pending = matcher.toMatchResult();
}
return pending != null;
}
public MatchResult next() {
// Fill pending if necessary (as when clients call next() without
// checking hasNext()), throw if not possible.
if (!hasNext()) { throw new NoSuchElementException(); }
// Consume pending so next call to hasNext() does a find().
MatchResult next = pending;
pending = null;
return next;
}
/** Required to satisfy the interface, but unsupported. */
public void remove() { throw new UnsupportedOperationException(); }
};
}
};
}
With this,
for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
System.out.println(match.group() + " at " + match.start());
}
yields
a at 0 b at 1 a at 3 c at 4 a at 5 a at 7 b at 8 a at 10
Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.
1.in my htaccess file that lives in my wp-content folder i add this below what's already there
<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>
In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.
2.) In my ajax code i can then use my url like this
$.ajax({
url:'/wp-content/themes/themeName/forms.php',
data:({
someVar: someValue
}),
type: 'POST'
});
obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.
Had the same problem, regenerating application key helped - php artisan key:generate
As per the Javadoc, the MimeMessage#setText()
sets a default mime type of text/plain
, while you need text/html
. Rather use MimeMessage#setContent()
instead.
message.setContent(someHtmlMessage, "text/html; charset=utf-8");
For additional details, see:
You can use these options as well, either use \footnotesize
or \tiny
. This would really help in fitting big tables.
\begin{table}[htbp]
\footnotesize
\caption{Information on making the table size small}
\label{table:table1}
\begin{tabular}{ll}
\toprule
S.No & HMD \\
\midrule
1 & HTC Vive \\
2 & HTC Vive Pro \\
\bottomrule
\end{tabular}
\end{table}
The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.
g.d.d.c. is right, but adding a very frequent example:
You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType
. In that case, you can get this error. So before accessing an attribute of that parameter check if it's not NoneType
.
I was inspired of Jason's function and made a little improvements to it and got as a result rather fast finder:
function timo_longest(a) {
var c = 0, d = 0, l = 0, i = a.length;
if (i) while (i--) {
d = a[i].length;
if (d > c) {
l = i; c = d;
}
}
return a[l];
}
arr=["First", "Second", "Third"];
var longest = timo_longest(arr);
Speed results: http://jsperf.com/longest-string-in-array/7
>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True, True, True, True],
[ True, True, True, True]], dtype=bool)
numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
I will add my answer to cover all cases:
My solution was unistalling EntityFramework from NuGet Package Manager and then I was prompted to restart Visual Studio because it couldn't "finalize the uninstall".
I restarted Visual Studio and reinstalled EntityFramework then my problem was solved.
Hope this helps someone!
Try escaping those characters:
[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
To base64-encode a UInt8Array
with arbitrary data (not necessarily UTF-8) using native browser functionality:
const base64_arraybuffer = async (data) => {
// Use a FileReader to generate a base64 data URI
const base64url = await new Promise((r) => {
const reader = new FileReader()
reader.onload = () => r(reader.result)
reader.readAsDataURL(new Blob([data]))
})
/*
The result looks like
"data:application/octet-stream;base64,<your base64 data>",
so we split off the beginning:
*/
return base64url.split(",", 2)[1]
}
// example use:
await base64_arraybuffer(new UInt8Array([1,2,3,100,200]))
Stephen Taub has implemented a solution to this question, see Building Async Coordination Primitives, Part 7: AsyncReaderWriterLock.
Stephen Taub is highly regarded in the industry, so anything he writes is likely to be solid.
I won't reproduce the code that he posted on his blog, but I will show you how to use it:
/// <summary>
/// Demo class for reader/writer lock that supports async/await.
/// For source, see Stephen Taub's brilliant article, "Building Async Coordination
/// Primitives, Part 7: AsyncReaderWriterLock".
/// </summary>
public class AsyncReaderWriterLockDemo
{
private readonly IAsyncReaderWriterLock _lock = new AsyncReaderWriterLock();
public async void DemoCode()
{
using(var releaser = await _lock.ReaderLockAsync())
{
// Insert reads here.
// Multiple readers can access the lock simultaneously.
}
using (var releaser = await _lock.WriterLockAsync())
{
// Insert writes here.
// If a writer is in progress, then readers are blocked.
}
}
}
If you want a method that's baked into the .NET framework, use SemaphoreSlim.WaitAsync
instead. You won't get a reader/writer lock, but you will get tried and tested implementation.
Member references are usually considered bad. They make life hard compared to member pointers. But it's not particularly unsual, nor is it some special named idiom or thing. It's just aliasing.
worked for me too:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parsed = null;
try {
parsed = sdf.parse("02/01/2014");
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.sql.Date data = new java.sql.Date(parsed.getTime());
contato.setDataNascimento( data);
// Contato DataNascimento era Calendar
//contato.setDataNascimento(Calendar.getInstance());
// grave nessa conexão!!!
ContatoDao dao = new ContatoDao("mysql");
// método elegante
dao.adiciona(contato);
System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
To "unapply" the most (recent?) migration after it has already been applied to the database:
Hope this helps and is applicable to any migration in the project... I tested this out only to the most recent migration...
Happy coding!
You can use jQuery’s show()
and hide()
methods. Like below:
JQuery:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var val = $(this).attr("value");
var target = $("." + val);
$(".msg").not(target).hide();
$(target).show();
});
});
HTML:
<input type="radio" name="color" value="yellow"> Yellow
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<div class="yellow msg">You have selected Yellow</div>
<div class="red msg">You have selected Red</div>
<div class="green msg">You have selected Green</div>
Here is an example: Show/hide DIV based on Radio Button click
In version r82 of Three.js TextureLoader is the object to use for loading a texture.
Extract (test.js):
var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
0.1, 50);
var renderer = ...
[...]
/**
* Will be called when load completes.
* The argument will be the loaded texture.
*/
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(20, 20, 20);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var mesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(mesh);
var render = function () {
requestAnimationFrame(render);
mesh.rotation.x += 0.010;
mesh.rotation.y += 0.010;
renderer.render(scene, camera);
};
render();
}
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (xhr) {
console.log('An error happened');
};
var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);
In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.
Extract (Globe.js):
Create a new container using Object3D
for having two meshes in the same container:
var Globe = function (radius, segments) {
THREE.Object3D.call(this);
this.name = "Globe";
var that = this;
// instantiate a loader
var loader = new THREE.TextureLoader();
A map called textures
where every object contains the url
of a texture file and val
for storing the value of a Three.js texture object.
// earth textures
var textures = {
'map': {
url: 'relief.jpg',
val: undefined
},
'bumpMap': {
url: 'elev_bump_4k.jpg',
val: undefined
},
'specularMap': {
url: 'wateretopo.png',
val: undefined
}
};
The array of promises, for each object in the map called textures
push a new Promise in the array texturePromises
, every Promise will call loader.load
. If the value of entry.val
is a valid THREE.Texture
object, then resolve the promise.
var texturePromises = [], path = './';
for (var key in textures) {
texturePromises.push(new Promise((resolve, reject) => {
var entry = textures[key]
var url = path + entry.url
loader.load(url,
texture => {
entry.val = texture;
if (entry.val instanceof THREE.Texture) resolve(entry);
},
xhr => {
console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
'% loaded');
},
xhr => {
reject(new Error(xhr +
'An error occurred loading while loading: ' +
entry.url));
}
);
}));
}
Promise.all
takes the promise array texturePromises
as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.
// load the geometry and the textures
Promise.all(texturePromises).then(loadedTextures => {
var geometry = new THREE.SphereGeometry(radius, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: textures.map.val,
bumpMap: textures.bumpMap.val,
bumpScale: 0.005,
specularMap: textures.specularMap.val,
specular: new THREE.Color('grey')
});
var earth = that.earth = new THREE.Mesh(geometry, material);
that.add(earth);
});
For the cloud sphere only one texture is necessary:
// clouds
loader.load('n_amer_clouds.png', map => {
var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: map,
transparent: true
});
var clouds = that.clouds = new THREE.Mesh(geometry, material);
that.add(clouds);
});
}
Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;
In my case it was because I didn't connect to databases yet when first opened solution. click connection manager tab, establish connection to every datasource in that tab, run project
Kotlin solution to move an Element from "fromPos" to "toPos" and shift all other items accordingly (useful for moving an item in a staggered layout recyclerView in an Android application)
if(fromPos < toPos){
val movingElement = myList[fromPos]
//shifts all elements between fromPos and toPos 1 down
for(i in fromPos+1..toPos){
myList[i-1] = myList[i]
}
//re-add element that was saved in the beginning
myList[toPos] = movingElement
}
if(fromPos > toPos){
val movingElement = myList[fromPos]
//shifts elements between toPos and fromPos 1 up
for(i in fromPos downTo toPos+1){
myList[i] = myList[i-1]
}
//re-add element that was saved in the beginning
myList[toPos] = movingElement
}
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Try to think in terms of a model and what happens to that model when a checkbox is checked.
Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:
<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />
and in the controller:
$scope.fooSelected = false;
$scope.baaSelected = false;
The next button should only be available under certain circumstances so add the ng-disabled directive to the button:
<button type='button' ng-disabled='nextButtonDisabled'></button>
Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:
$scope.$watch('[fooSelected,baaSelected]', function(){
$scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );
The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.
(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)
To correct this error, you need to go into your Project Properties
(and/or those of the libraries you are using,) then into C/C++
, then Code Generation
, and check the value of Runtime Library
; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.
Consider for example that the above two pieces of code are called A
and B
. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE
object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.
What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER
instead of LocationManager.GPS_PROVIDER
. The NETWORK_PROVIDER
will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.
http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.
After you get done with most of the code in OnCreate()
, add this:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You could also have your activity implement the LocationListener
class and thus implement onLocationChanged()
in your activity.
You can replace the jquery load function with a version that has cache set to false.
(function($) {
var _load = jQuery.fn.load;
$.fn.load = function(url, params, callback) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if (off > -1) {
selector = stripAndCollapse(url.slice(off));
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
cache: false,
data: params
}).done(function(responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
}).always(callback && function(jqXHR, status) {
self.each(function() {
callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
});
});
}
return this;
}
})(jQuery);
Place this somewhere global where it will run after jquery loads and you should be all set. Your existing load code will no longer be cached.
Just a matter of the right google search:
data = dat_1.append(dat_2)
data = data.groupby(data.index).sum()
I had content that was longer than the dialog. On open, the dialog would scoll to the first :tabbable which was at the bottom. Here was my fix.
$("#myDialog").dialog({
...
open: function(event, ui) { $(this).scrollTop(0); }
});
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
For this problem, I do a help function like this:
const char* name(Id id) {
struct Entry {
Id id;
const char* name;
};
static const Entry entries[] = {
{ ErrorA, "ErrorA" },
{ ErrorB, "ErrorB" },
{ 0, 0 }
}
for (int it = 0; it < gui::SiCount; ++it) {
if (entries[it].id == id) {
return entries[it].name;
}
}
return 0;
}
Linear search is usually more efficient than std::map
for small collections like this.
This line is your problem:
lstemail.Add("JOhn","Smith","Los Angeles");
There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add()
an instance of the class to lstemail
:
lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });
In Charles, go to Proxy>>Proxy Settings and select the SSL tab. Add your host to the list of Locations.
For example, if your secure call is going to https://secure.example.com, you can enter secure.example.com, or *.example.com.
Once the above is in place, you may need to right-click on the call in the main Charles window and select the SSL Proxying option.
Hope this helps.
In Chart.js version 2.0 this is possible:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See axes labelling documentation for more details.
// person.js
'use strict';
module.exports = class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
display() {
console.log(this.firstName + " " + this.lastName);
}
}
// index.js
'use strict';
var Person = require('./person.js');
var someone = new Person("First name", "Last name");
someone.display();
Previous answer didn't work for me.
But this worked perfectly. Convert Data URI to File then append to FormData
or you can use the following to compile the all java source files in current directory..
javac *.java
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
@Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
To select columns to plot, I added 2 lines to Vincent Zoonekynd's answer:
#convert to tall/long format(from wide format)
col_plot = c("A","B")
dlong <- melt(d[,c("Xax", col_plot)], id.vars="Xax")
#"value" and "variable" are default output column names of melt()
ggplot(dlong, aes(Xax,value, col=variable)) +
geom_point() +
geom_smooth()
Google "tidy data" to know more about tall(or long)/wide format.
This is almost certainly going to be true given that SSL requires an extra step of encryption that simply isn't required by non-SLL HTTP.
It's not basic css, but if you're using LESS (http://lesscss.org), you can do this using recursion:
.hClass (@index) when (@index > 0) {
h@{index} {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
.hClass(@index - 1);
}
.hClass(6);
Sass (http://sass-lang.com) will allow you to manage this, but won't allow recursion; they have @for
syntax for these instances:
@for $index from 1 through 6 {
h#{$index}{
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
}
If you're not using a dynamic language that compiles to CSS like LESS or Sass, you should definitely check out one of these options. They can really simplify and make more dynamic your CSS development.
Well, base on your code, you would put onkeyup=sum() in each text box txt1 and txt2
You should not replace the text entirely. Add the text after the "# END WordPress".
you can put the input inside a form like this:-
<script>
$(document).ready(function(){
$(document).on('click','#send', function(){
$('#hid').val(data)
document.forms["myForm"].submit();
})
})
</script>
<form id="myForm" action="/request_page url/" method="post">
<input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>
Use replace()
s = s.replace("'", "\\'");
output:
You\'ll be totally awesome, I\'m really terrible
Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page
.
So its easy as changing:
$(document).scroll(function() { // OR $(window).scroll(function() {
didScroll = true;
});
to
$('div#page').scroll(function() {
didScroll = true;
});
Also; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "AnotherViewController")
self.navigationController?.pushViewController(controller, animated: true)
}
}
import UIKit
class AnotherViewController: UIViewController {
var name : String!
deinit {
print("Deint AnotherViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
print(CFGetRetainCount(self))
/*
When you test please comment out or vice versa
*/
// // Should not use unowned here. Because unowned is used where not deallocated. or gurranted object alive. If you immediate click back button app will crash here. Though there will no retain cycles
// clouser(string: "") { [unowned self] (boolValue) in
// self.name = "some"
// }
//
//
// // There will be a retain cycle. because viewcontroller has a strong refference to this clouser and as well as clouser (self.name) has a strong refferennce to the viewcontroller. Deint AnotherViewController will not print
// clouser(string: "") { (boolValue) in
// self.name = "some"
// }
//
//
// // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser (self.name) has a weak refferennce to the viewcontroller. Deint AnotherViewController will print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
//
// clouser(string: "") { [weak self] (boolValue) in
// self?.name = "some"
// }
// no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser nos refference to the viewcontroller. Deint AnotherViewController will print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
clouser(string: "") { (boolValue) in
print("some")
print(CFGetRetainCount(self))
}
}
func clouser(string: String, completion: @escaping (Bool) -> ()) {
// some heavy task
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
completion(true)
}
}
}
If you do not sure about
[unowned self]
then use[weak self]
Here is a very simple popup:
<!DOCTYPE html>
<html>
<head>
<style>
#modal {
position:absolute;
background:gray;
padding:8px;
}
#content {
background:white;
padding:20px;
}
#close {
position:absolute;
background:url(close.png);
width:24px;
height:27px;
top:-7px;
right:-7px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var modal = (function(){
// Generate the HTML and add it to the document
$modal = $('<div id="modal"></div>');
$content = $('<div id="content"></div>');
$close = $('<a id="close" href="#"></a>');
$modal.hide();
$modal.append($content, $close);
$(document).ready(function(){
$('body').append($modal);
});
$close.click(function(e){
e.preventDefault();
$modal.hide();
$content.empty();
});
// Open the modal
return function (content) {
$content.html(content);
// Center the modal in the viewport
$modal.css({
top: ($(window).height() - $modal.outerHeight()) / 2,
left: ($(window).width() - $modal.outerWidth()) / 2
});
$modal.show();
};
}());
// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
$('a#popup').click(function(e){
modal("<p>This is popup's content.</p>");
e.preventDefault();
});
});
</script>
</head>
<body>
<a id='popup' href='#'>Simple popup</a>
</body>
</html>
More flexible solution can be found in this tutorial: http://www.jacklmoore.com/notes/jquery-modal-tutorial/ Here's close.png for the sample.
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
Yes to output {
in string.Format
you have to escape it like this {{
So this
String val = "1,2,3";
String.Format(" foo {{{0}}}", val);
will output "foo {1,2,3}"
.
BUT you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}
int i = 24;
string str = String.Format("{{{0:N}}}", i); //gives '{N}' instead of {24.00}
But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case you have to use this instead.
String.Format("{0}{1:N}{2}", "{", i, "}") //evaluates to {24.00}
Reference Articles String.Format gottach and String Formatting FAQ
use typeid(class).name
// illustratory code assuming all includes/namespaces etc
#include <iostream>
#include <typeinfo>
using namespace std;
struct A{};
int main(){
cout << typeid(A).name();
}
It is important to remember that this gives an implementation defined names.
As far as I know, there is no way to get the name of the object at run time reliably e.g. 'A' in your code.
EDIT 2:
#include <typeinfo>
#include <iostream>
#include <map>
using namespace std;
struct A{
};
struct B{
};
map<const type_info*, string> m;
int main(){
m[&typeid(A)] = "A"; // Registration here
m[&typeid(B)] = "B"; // Registration here
A a;
cout << m[&typeid(a)];
}
PostgreSQL is integrated in Server.app available through the App Store in Mac OS X v10.8 (Mountain Lion). That means that it is already configured, and you only need to launch it, and then create users and databases.
Tip: Do not start with defining $PGDATA and so on. Take file locations as is.
You would have this file: /Library/Server/PostgreSQL/Config/org.postgresql.postgres.plist
To start:
sudo serveradmin start postgres
Process started with arguments:
/Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL/Data -c listen_addresses=127.0.0.1,::1 -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL.log -c log_line_prefix=%t -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/private/var/pgsql_socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770
You can sudo:
sudo -u _postgres psql template1
Or connect:
psql -h localhost -U _postgres postgres
You can find the data directory, version, running status and so forth with
sudo serveradmin fullstatus postgres
With Android API level (23), we are required to check for permissions. https://developer.android.com/training/permissions/requesting.html
I had your same problem, but the following worked for me and I am able to retrieve Location data successfully:
(1) Ensure you have your permissions listed in the Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
(2) Ensure you request permissions from the user:
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
}
(3) Ensure you use ContextCompat as this has compatibility with older API levels.
(4) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
(5) This approach only worked for me after I included @TargetApi(23) at the top of my initLocationService method.
(6) I also added this to my gradle build:
compile 'com.android.support:support-v4:23.0.1'
Here is my LocationService for reference:
public class LocationService implements LocationListener {
//The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private final static boolean forceNetwork = false;
private static LocationService instance = null;
private LocationManager locationManager;
public Location location;
public double longitude;
public double latitude;
/**
* Singleton implementation
* @return
*/
public static LocationService getLocationManager(Context context) {
if (instance == null) {
instance = new LocationService(context);
}
return instance;
}
/**
* Local constructor
*/
private LocationService( Context context ) {
initLocationService(context);
LogService.log("LocationService created");
}
/**
* Sets up location service after permissions is granted
*/
@TargetApi(23)
private void initLocationService(Context context) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
try {
this.longitude = 0.0;
this.latitude = 0.0;
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (forceNetwork) isGPSEnabled = false;
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
//else
{
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateCoordinates();
}
}//end if
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateCoordinates();
}
}
}
} catch (Exception ex) {
LogService.log( "Error creating location service: " + ex.getMessage() );
}
}
@Override
public void onLocationChanged(Location location) {
// do stuff here with location object
}
}
I tested with an Android Lollipop device so far only. Hope this works for you.
Swift 3
To set the same appearance of navigation Bar across your app, you can do this in AppDelegate.swift:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupNavigationBarAppearence()
return true
}
private func setupNavigationBarAppearence(){
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.isTranslucent = false
//nav bar color
navigationBarAppearace.barTintColor = UIColor.primaryColor()
//SETS navbar title string to white
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
//Makes the batery icon an any other icon of the device to white.
navigationBarAppearace.barStyle = .black
}
Personnally, I prefer:
var result = from entry in table
where (entry.something??0)==(value??0)
select entry;
over
var result = from entry in table
where (value == null ? entry.something == null : entry.something == value)
select entry;
because it prevents repetition -- though that's not mathematically exact, but it fits well most cases.
The other answers didn't work for me, I guess something wrong happens between ButterKnife and 3.0.0 alpha5.
However, I found that when I annotated any one sentence, either BUtterKnife or 3.0.0 alpha5, it works normally.
So, you should just avoid the duplication or conflict.
I have fast solution. Just create a file ImageUtil.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
public class ImageUtil
{
public static Bitmap convert(String base64Str) throws IllegalArgumentException
{
byte[] decodedBytes = Base64.decode(
base64Str.substring(base64Str.indexOf(",") + 1),
Base64.DEFAULT
);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}
Usage:
Bitmap bitmap = ImageUtil.convert(base64String);
or
String base64String = ImageUtil.convert(bitmap);
$(document).ready(function() {
//calculate the window height & add css properties for height 100%
wh = $( window ).height();
ww = $( window ).width();
$(".targeted-div").css({"height": wh, "width": ww});
});
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
The second parameter of window.open() is a string representing the name of the target window.
Set it to: "_self".
<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>
Sidenote:
The following question gives an overview of an arguably better way to bind event handlers to HTML links.
Following are the most commonly used calls for downloading files in python:
urllib.urlretrieve ('url_to_file', file_name)
urllib2.urlopen('url_to_file')
requests.get(url)
wget.download('url', file_name)
Note: urlopen
and urlretrieve
are found to perform relatively bad with downloading large files (size > 500 MB). requests.get
stores the file in-memory until download is complete.
Just do simple things to import the .py file from a different folder.
Let's say you have a directory like:
lib/abc.py
Then just keep an empty file in lib folder as named
__init__.py
And then use
from lib.abc import <Your Module name>
Keep the __init__.py
file in every folder of the hierarchy of the import module.
From this brilliant blog post... https://blog.josephscott.org/2011/10/14/timing-details-with-curl/
cURL supports formatted output for the details of the request (see the cURL manpage for details, under -w, –write-out <format>
). For our purposes we’ll focus just on the timing details that are provided. Times below are in seconds.
Create a new file, curl-format.txt, and paste in:
time_namelookup: %{time_namelookup}s\n
time_connect: %{time_connect}s\n
time_appconnect: %{time_appconnect}s\n
time_pretransfer: %{time_pretransfer}s\n
time_redirect: %{time_redirect}s\n
time_starttransfer: %{time_starttransfer}s\n
----------\n
time_total: %{time_total}s\n
Make a request:
curl -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"
Or on Windows, it's...
curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"
-w "@curl-format.txt"
tells cURL to use our format file
-o /dev/null
redirects the output of the request to /dev/null
-s
tells cURL not to show a progress meter
"http://wordpress.com/"
is
the URL we are requesting. Use quotes particularly if your URL has "&" query string parameters
time_namelookup: 0.001s
time_connect: 0.037s
time_appconnect: 0.000s
time_pretransfer: 0.037s
time_redirect: 0.000s
time_starttransfer: 0.092s
----------
time_total: 0.164s
alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "
Then you can simply call...
curltime wordpress.org
Thanks to commenter Pete Doyle!
This script does not require a separate .txt file to contain the formatting.
Create a new file, curltime, somewhere in your executable path, and paste in:
#!/bin/bash
curl -w @- -o /dev/null -s "$@" <<'EOF'
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
EOF
Call the same way as the alias:
curltime wordpress.org
Put this command in CURLTIME.BAT (in the same folder as curl.exe)
curl -w "@%~dp0curl-format.txt" -o NUL -s %*
Then you can simply call...
curltime wordpress.org
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
TimeUnit is an enum, so you can't create a new one.
The following will convert 1000000000000ns to seconds.
TimeUnit.NANOSECONDS.toSeconds(1000000000000L);
Have a look at the example in this link :
http://docs.angularjs.org/api/ngSanitize.$sanitize
Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :
If you already have done all this :
// My magic HTML string function.
function htmlString (str) {
return "<h1>" + str + "</h1>";
}
function Ctrl ($scope) {
var str = "HELLO!";
$scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];
Then in your html within the scope of that controller, you could
<div ng-bind-html="htmlString"></div>
Try lftp
lftp -u $user,$pass sftp://$host << --EOF--
cd $directory
put $srcfile
quit
--EOF--
If you want nice button with rounded corners, then use this class:
.link_button {_x000D_
-webkit-border-radius: 4px;_x000D_
-moz-border-radius: 4px;_x000D_
border-radius: 4px;_x000D_
border: solid 1px #20538D;_x000D_
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);_x000D_
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
background: #4479BA;_x000D_
color: #FFF;_x000D_
padding: 8px 12px;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#" class="link_button">Example</a>
_x000D_
If you editing info.plist
directly, below should help you, don't key in "YES" as string below:
<key>UIFileSharingEnabled</key>
<string>YES</string>
You should use this:
<key>UIFileSharingEnabled</key>
<true/>
This page seems to be a good central location for posting suggestions about the Fragment IllegalArgumentException. Here is one more thing you can try. This is what finally worked for me:
I had forgotten that I had a separate layout file for landscape orientation. After I added my FrameLayout container there, too, the fragment worked.
On a separate note, if you have already tried everything else suggested on this page (and the entire Internet, too) and have been pulling out your hair for hours, consider just dumping these annoying fragments and going back to a good old standard layout. (That's actually what I was in the process of doing when I finally discovered my problem.) You can still use the container concept. However, instead of filling it with a fragment, you can use the xml include
tag to fill it with the same layout that you would have used in your fragment. You could do something like this in your main layout:
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/former_fragment_layout" />
</FrameLayout>
where former_fragment_layout
is the name of the xml layout file that you were trying to use in your fragment. See Re-using Layouts with include for more info.
Just use:
$("input:empty").length == 0;
If it's zero, none are empty.
To be a bit smarter though and also filter out items with just spaces in, you could do:
$("input").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
In case you are using GLib, it has two functions for that, g_strreverse() and g_utf8_strreverse()
There are two ways we can convert String to InputStream in Java,
Example :-
String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
Example:-
String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
The .encode
method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs
module in the standard library and codecs.open
in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv
module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv
module level), of the form line.decode('whateverweirdcodec').encode('utf-8')
-- but probably you can just use the name of your existing encoding in the yield
line in my code above, instead of 'utf-8'
, as csv
is actually going to be just fine with ISO-8859-* encoded bytestrings.
Use decode
:
print(curses.version.decode())
# 2.2
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
I'd like to add to Jonas' answer. Spinning on a bool
will cause 100% CPU utilization, and waste a bunch of energy doing a lot of nothing while waiting for CTRL+C.
The better solution is to use a ManualResetEvent
to actually "wait" for the CTRL+C:
static void Main(string[] args) {
var exitEvent = new ManualResetEvent(false);
Console.CancelKeyPress += (sender, eventArgs) => {
eventArgs.Cancel = true;
exitEvent.Set();
};
var server = new MyServer(); // example
server.Run();
exitEvent.WaitOne();
server.Stop();
}
To use shorthand to get the direction:
int direction = column == 0
? 0
: (column == _gridSize - 1 ? 1 : rand.Next(2));
To simplify the code entirely:
if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}
As accepted answer has provided required info, and for more info about using and disabling App Transport Security one can find more on this.
For Per-Domain Exceptions add these to the Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
But What If I Don’t Know All the Insecure Domains I Need to Use? Use following key in your Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Use the in_array()
function.
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
if (in_array('kitchen', $array)) {
echo 'this array contains kitchen';
}
As of PHP 5.6 @$filePath
will not work in CURLOPT_POSTFIELDS
without CURLOPT_SAFE_UPLOAD
being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.
$fields = [
'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);
XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.
XWAMPP/WAMP - Windows,Apache,Mysql,PHP
IIS - Apache,SQL Server, ASP.NET
If you like to read more about XWAMPP vs WAMP
Add to your panel's style code something like this:
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>