you want these four lines of code in your Run.bat:
@echo off //this makes it so you have an empty cmd window on startup
javac Main.java //this compiles the .java into a .class
java Main // this runs the .class file
pause //this prevents the window from instantly closing after program end
apt–get: command not found
For Debian based Linux distributions:
Try to use sudo apt install <package>
instead of the usual sudo apt-get install <package>
From man apt
apt provides a high-level commandline interface for the package management system. It is intended as an end user interface and enables some options better suited for interactive usage by default compared to more specialized APT tools like apt-get(8) and apt-cache(8).
I was having a similar problem. (No problems training with GradientDescent optimizer, but error raised when using to Adam Optimizer, or any other optimizer with its own variables)
Changing to an interactive session solved this problem for me.
sess = tf.Session()
into
sess = tf.InteractiveSession()
I simply do
git push -u origin localBranch:remoteBranchToBeCreated
over an already cloned project.
Git creates a new branch named remoteBranchToBeCreated
under my commits I did in localBranch
.
Edit: this changes your current local branch's (possibly named localBranch
) upstream to origin/remoteBranchToBeCreated
. To fix that, simply type:
git branch --set-upstream-to=origin/localBranch
or
git branch -u origin/localBranch
So your current local branch now tracks origin/localBranch
back.
If all you have is the iterator, then no, there is no "better" way. If the iterator comes from a collection you could as that for size.
Keep in mind that Iterator is just an interface for traversing distinct values, you would very well have code such as this
new Iterator<Long>() {
final Random r = new Random();
@Override
public boolean hasNext() {
return true;
}
@Override
public Long next() {
return r.nextLong();
}
@Override
public void remove() {
throw new IllegalArgumentException("Not implemented");
}
};
or
new Iterator<BigInteger>() {
BigInteger next = BigInteger.ZERO;
@Override
public boolean hasNext() {
return true;
}
@Override
public BigInteger next() {
BigInteger current = next;
next = next.add(BigInteger.ONE);
return current;
}
@Override
public void remove() {
throw new IllegalArgumentException("Not implemented");
}
};
This gets you X and X' as variant arrays you can pass to another function.
Dim X() As Variant
Dim XT() As Variant
X = ActiveSheet.Range("InRng").Value2
XT = Application.Transpose(X)
To have the transposed values as a range, you have to pass it via a worksheet as in this answer. Without seeing how your covariance function works it's hard to see what you need.
Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".
If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :
var peoples = {
"bob": { "dinner": "pizza" },
"john": { "dinner": "sushi" },
"larry" { "dinner": "hummus" }
};
// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];
// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;
Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.
Checking status in functional manner
assert_exit_status() {
lambda() {
local val_fd=$(echo $@ | tr -d ' ' | cut -d':' -f2)
local arg=$1
shift
shift
local cmd=$(echo $@ | xargs -E ':')
local val=$(cat $val_fd)
eval $arg=$val
eval $cmd
}
local lambda=$1
shift
eval $@
local ret=$?
$lambda : <(echo $ret)
}
Usage:
assert_exit_status 'lambda status -> [[ $status -ne 0 ]] && echo Status is $status.' lls
Output
Status is 127
class MyApp2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 0,
color: Colors.blueAccent,
)
),
title: 'Welcome to flutter ',
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int number = 0;
void _increment(){
setState(() {
number ++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
appBar: AppBar(
title: Text('MyApp2'),
leading: Icon(Icons.menu),
// backgroundColor: Colors.blueAccent,
),
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200.0),
topRight: Radius.circular(200)
),
color: Colors.white,
),
)
);
}
}
In my case the reason for the error was an runtime error in my corresponding java class. I fixed it and all was ok. My tip: don't search for an "location not set"
You can see your current session settings by querying nls_session_parameters
:
select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';
VALUE
----------------------------------------
.,
That may differ from the database defaults, which you can see in nls_database_parameters
.
In this session your query errors:
select to_number('100,12') from dual;
Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 - "invalid number"
I could alter my session, either directly with alter session
or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):
alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;
TO_NUMBER('100,12')
-------------------
100,12
In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.
But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number()
; though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:
alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;
TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
100.12
By default the result is still displayed with my session settings, so the decimal separator is still a period.
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
I forgot I had mine attached to Visual Studio debugger. Be sure to disconnect from there, and then wait a moment. Otherwise killing the process viewing the PID from the Worker Processes functionality of IIS manager will work too.
d = {}
will create a new instance for d
but all other references will still point to the old contents.
d.clear()
will reset the contents, but all references to the same instance will still be correct.
PHP's perdefined apache_get_modules()
function returns a list of enabled modules. To check if mod_rewrite
is enabled , you can run the following script on your server :
<?php
print_r(apache_get_modules());
?>
If the above example fails, you can verify mod-rewrite using your .htaccess
file.
Create an htaccess
file in the document root and add the following rewriteRule :
RewriteEngine on
RewriteRule ^helloWorld/?$ /index.php [NC,L]
Now visit http://example.com/HelloWorld , You will be internally forwarded to /index.php page of your site. Otherwise, if mod-rewrite is disabled , you will get a 500 Internel server error.
Hope this helps.
I struggled understanding how to do this on my first implementation - make sure you have the following:
1) Your device supports vibration (my Samsung tablet did not work so I kept re-checking the code - the original code worked perfectly on my CM Touchpad
2) You have declared above the application level in your AndroidManifest.xml file to give the code permission to run.
3) Have imported both of the following in to your MainActivity.java with the other imports: import android.content.Context; import android.os.Vibrator;
4) Call your vibration (discussed extensively in this thread already) - I did it in a separate function and call this in the code at other points - depending on what you want to use to call the vibration you may need an image (Android: long click on a button -> perform actions) or button listener, or a clickable object as defined in XML (Clickable image - android):
public void vibrate(int duration)
{
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
The reason your code isn't working the way you would expect is because this line:
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
should be changed to:
<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>
There are two things to notice here:
1: The "
s around datepicker
have been changed to '
s so that they do not interfere with the quotes surrounding the onclick
event.
2: The click()
has been changed to focus()
to activate the datepicker calendar. When the button is pressed.
Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
, this should not be a problem.
Inline events are not recommended.
I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web
Just use the indexer and update directly:
dictionary["cat"] = 3
Please check this gist.
https://gist.github.com/ecdundar/789660d830d6d40b6c90
#!/bin/bash
# copymysql.sh
# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200
MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"
REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "
LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "
IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema' ;"
# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`
# COPY ALL TABLES
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
IGNOREVIEWS=""
for view in $views; do
IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view "
done
echo "TABLES "$db
$MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
$MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction $db | mysql $LOCALCONNECTION $db
done
# COPY ALL PROCEDURES
for db in $databases; do
echo "PROCEDURES "$db
#PROCEDURES
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL TRIGGERS
for db in $databases; do
echo "TRIGGERS "$db
#TRIGGERS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL VIEWS
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
MYVIEWS=""
for view in $views; do
MYVIEWS=${MYVIEWS}" "$view" "
done
echo "VIEWS "$db
if [ -n "$MYVIEWS" ]; then
#VIEWS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
fi
done
echo "OK!"
You have two ways to do that:
METHOD 1. The secure way.
Put the images on /www/htdocs/
<?php
$www_root = 'http://localhost/images';
$dir = '/var/www/images';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
break;
}
}
}
?>
METHOD 2. Unsecure but more flexible.
Put the images on any directory (apache must have permission to read the file).
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
break;
}
}
}
?>
And create another script to read the image file.
<?php
$filename = base64_decode($_GET['file']);
// Check the folder location to avoid exploit
if (dirname($filename) == '/home/user/Pictures')
echo file_get_contents($filename);
?>
I usually just add the following custom CSS, the W3School example prepended with cursor-
.cursor-alias {cursor: alias;}_x000D_
.cursor-all-scroll {cursor: all-scroll;}_x000D_
.cursor-auto {cursor: auto;}_x000D_
.cursor-cell {cursor: cell;}_x000D_
.cursor-context-menu {cursor: context-menu;}_x000D_
.cursor-col-resize {cursor: col-resize;}_x000D_
.cursor-copy {cursor: copy;}_x000D_
.cursor-crosshair {cursor: crosshair;}_x000D_
.cursor-default {cursor: default;}_x000D_
.cursor-e-resize {cursor: e-resize;}_x000D_
.cursor-ew-resize {cursor: ew-resize;}_x000D_
.cursor-grab {cursor: -webkit-grab; cursor: grab;}_x000D_
.cursor-grabbing {cursor: -webkit-grabbing; cursor: grabbing;}_x000D_
.cursor-help {cursor: help;}_x000D_
.cursor-move {cursor: move;}_x000D_
.cursor-n-resize {cursor: n-resize;}_x000D_
.cursor-ne-resize {cursor: ne-resize;}_x000D_
.cursor-nesw-resize {cursor: nesw-resize;}_x000D_
.cursor-ns-resize {cursor: ns-resize;}_x000D_
.cursor-nw-resize {cursor: nw-resize;}_x000D_
.cursor-nwse-resize {cursor: nwse-resize;}_x000D_
.cursor-no-drop {cursor: no-drop;}_x000D_
.cursor-none {cursor: none;}_x000D_
.cursor-not-allowed {cursor: not-allowed;}_x000D_
.cursor-pointer {cursor: pointer;}_x000D_
.cursor-progress {cursor: progress;}_x000D_
.cursor-row-resize {cursor: row-resize;}_x000D_
.cursor-s-resize {cursor: s-resize;}_x000D_
.cursor-se-resize {cursor: se-resize;}_x000D_
.cursor-sw-resize {cursor: sw-resize;}_x000D_
.cursor-text {cursor: text;}_x000D_
.cursor-w-resize {cursor: w-resize;}_x000D_
.cursor-wait {cursor: wait;}_x000D_
.cursor-zoom-in {cursor: zoom-in;}_x000D_
.cursor-zoom-out {cursor: zoom-out;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<button type="button" class="btn btn-success cursor-pointer">Sample Button</button>
_x000D_
One way to do it would be like this:
param(
[Parameter(Position=0)][String]$Vlan,
[Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
) ...
This would allow multiple hosts to be entered with spaces.
While this is not a direct answer to Devang's question I believe that the below macro can be very helpful to people looking to log BOOLs. This will log out the value of the bool as well as automatically labeling it with the name of the variable.
#define LogBool(BOOLVARIABLE) NSLog(@"%s: %@",#BOOLVARIABLE, BOOLVARIABLE ? @"YES" : @"NO" )
BOOL success = NO;
LogBool(success); // Prints out 'success: NO' to the console
success = YES;
LogBool(success); // Prints out 'success: YES' to the console
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Since git 1.8 (October 2012) you are able to do this from the command line:
git remote set-url origin --push --add user1@repo1
git remote set-url origin --push --add user2@repo2
git remote -v
Then git push
will push to user1@repo1, then push to user2@repo2.
Every platform is going to have a different approach to being able to generate keyboard events. This is because they each need to make use of system libraries (and system extensions). For a cross platform solution, you would need to take each of these solutions and wrap then into a platform check to perform the proper approach.
For windows, you might be able to use the pywin32 extension. win32api.keybd_event
win32api.keybd_event
keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
Simulate a keyboard event
Parameters
bVk : BYTE - Virtual-key code
bScan : BYTE - Hardware scan code
dwFlags=0 : DWORD - Flags specifying various function options
dwExtraInfo=0 : DWORD - Additional data associated with keystroke
You will need to investigate pywin32 for how to properly use it, as I have never used it.
If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):
for (int x = 1; x <= 50; x++)
{
list.Items.Add(x);
}
You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:
listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });
First, go to the following URL and download the mobile_detect.php file:
http://code.google.com/p/php-mobile-detect/
Insert the following code on your index or home page:
<?php
@include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
{
$detect = "false";
}
elseif ($detect->isMobile())
{
header("Location:http://www.yourmobiledirectory.com");
}
?>
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
You can write an extension to use it with all the UIViews eg. UIButton, UILabel, UIImageView etc. You can customise my following method as per your requirement, but I think it will work well for you.
extension UIView{
func setBorder(radius:CGFloat, color:UIColor = UIColor.clearColor()) -> UIView{
var roundView:UIView = self
roundView.layer.cornerRadius = CGFloat(radius)
roundView.layer.borderWidth = 1
roundView.layer.borderColor = color.CGColor
roundView.clipsToBounds = true
return roundView
}
}
Usage:
btnLogin.setBorder(7, color: UIColor.lightGrayColor())
imgViewUserPick.setBorder(10)
Here's an updated version with Kotlin I used assuming phone is higher than Honeycomb:
val actionBarHeight = with(TypedValue().also {context.theme.resolveAttribute(android.R.attr.actionBarSize, it, true)}) {
TypedValue.complexToDimensionPixelSize(this.data, resources.displayMetrics)
}
What does your "data variable" look like? If it's like this:
$mydate = "2010-05-12 13:57:01";
You can simply do:
$month = date("m",strtotime($mydate));
For more information, take a look at date and strtotime.
EDIT:
To compare with an int, just do a date_format($date,"n");
which will give you the month without leading zero.
Alternatively, try one of these:
if((int)$month == 1)...
if(abs($month) == 1)...
Or something weird using ltrim, round, floor... but date_format() with "n" would be the best.
//Vertical detection
var lastVelocityYSign = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentVelocityY = scrollView.panGestureRecognizer.velocity(in: scrollView.superview).y
let currentVelocityYSign = Int(currentVelocityY).signum()
if currentVelocityYSign != lastVelocityYSign &&
currentVelocityYSign != 0 {
lastVelocityYSign = currentVelocityYSign
}
if lastVelocityYSign < 0 {
print("SCROLLING DOWN")
} else if lastVelocityYSign > 0 {
print("SCOLLING UP")
}
}
Answer from Mos6y https://medium.com/@Mos6yCanSwift/swift-ios-determine-scroll-direction-d48a2327a004
For small scripts an optional way to make it readable is to use a variable like this:
awk -v fmt="'%s'\n" '{printf fmt, $1}'
I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable
There's also a shorthand ternary operator and it looks like this:
(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.
Example:
$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';
will return
Apples are great!
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
From the PHP Manual
Stephen Toub wrote a great article on implementing global keyboard hooks in C#:
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class InterceptKeys
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(
int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(
int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
It's for whose Hadoop is 2.6 and Spark is 1.6 and without "databricks" package.
import org.apache.spark.sql.types.{StructType,StructField,StringType,IntegerType};
import org.apache.spark.sql.Row;
val csv = sc.textFile("/path/to/file.csv")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0),row(1).toInt))
val schema = new StructType()
.add(StructField("id", StringType, true))
.add(StructField("val", IntegerType, true))
val df = sqlContext.createDataFrame(rdd, schema)
This solves even the problem with whitespaces:
In the original/source dir:
find . -type d -exec echo "'{}'" \; > dirs2.txt
then recreate it in the newly created dir:
mkdir -p <../<SOURCEDIR>/dirs2.txt
Crossframe-Scripting is not possible when the two frames have different domains -> Security.
See this: http://javascript.about.com/od/reference/a/frame3.htm
Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.
That work fine in Ajax call back to update select from JSON object
function UpdateList() {
var lsUrl = '@Url.Action("Action", "Controller")';
$.get(lsUrl, function (opdata) {
$.each(opdata, function (key, value) {
$('#myselect').append('<option value=' + key + '>' + value + '</option>');
});
});
}
Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>
You could use predefined utility type Record<Keys, Type>
:
const obj: Record<string, string> = {
property: "value",
};
It allows to specify keys for your object literal:
type Keys = "prop1" | "prop2"
const obj: Record<Keys, string> = {
prop1: "Hello",
prop2: "Aloha",
something: "anything" // TS Error: Type '{ prop1: string; prop2: string; something: string; }' is not assignable to type 'Record<Keys, string>'.
// Object literal may only specify known properties, and 'something' does not exist in type 'Record<Keys, string>'.
};
And a type for the property value:
type Keys = "prop1" | "prop2"
type Value = "Hello" | "Aloha"
const obj1: Record<Keys, Value> = {
prop1: "Hello",
prop2: "Hey", // TS Error: Type '"Hey"' is not assignable to type 'Value'.
};
Assuming that enum is numbered sequentially is error prone. Moreover, you may want to iterate over selected enumerators only. If that subset is small, looping over it explicitly might be an elegant choice:
enum Item { Man, Wolf, Goat, Cabbage }; // or enum class
for (auto item : {Wolf, Goat, Cabbage}) { // or Item::Wolf, ...
// ...
}
Another workaround is to use grep -o
with a little regex magic to get three chars followed by the end of line:
$ foo=1234567890
$ echo $foo | grep -o ...$
890
To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep
with this regex:
$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd
You can also use different ranges, such as 5,10
to get the last five to ten chars.
SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.
'does it mean that they wont be able to update 4 and 5 ?'
If your users in the doctor role are only in the doctor role, then yes.
However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.
More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
Removing and adding DOM element is slower than modification of existing one.
If your option sets have same length, you may do something like this:
$('#my-select option')
.each(function(index) {
$(this).text('someNewText').val('someNewValue');
});
In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.
I had the same problem when installing my application on the server when everything worked perfectly on localhost.
None of these solutions woorked, I always had the same error:
Could not find a part of the path 'C:\inetpub\wwwroot\myApp\bin\roslyn\csc.exe'
I ended up doing this:
bin/roslyn
folderpackages\Microsoft.Net.Compilers.1.3.2\tools
This solved my problem.
The above answers did not help me on Android, thanks to the Pshemo response that worked for me on Android. I will leave some of Pshemo's answer here :
split("\\\\n")
if you are new to proxy setup for Maven In my case first go and check your Home Folder weather there is .m2
folder and in it there should be a file named settings.xml
if not create it , and paste this and change host
and port
,then if needed change the nonProxyHosts
Home Folder - C:\Users\ {UserName}
<settings>
<proxies>
<proxy>
<id>httpproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>your-proxy-host</host>
<port>your-proxy-port</port>
<nonProxyHosts>localhost</nonProxyHosts>
</proxy>
<proxy>
<id>httpsproxy</id>
<active>true</active>
<protocol>https</protocol>
<host>your-proxy-host</host>
<port>your-proxy-port</port>
<nonProxyHosts>localhost</nonProxyHosts>
</proxy>
</proxies>
</settings>
If any case this does not success go and do the changes in this location of Home Folder
/conf/settings.xml
I am using Eclipse as my IDE
Hope this will help !!
Note:
To remove the proxy just move settings.xml
to some where else
@Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah)
to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
Refer this:
@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {
// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");
// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}
If you do run()
in main method, the thread of main method will invoke the run
method instead of the thread you require to run.
The start()
method creates new thread and for which the run()
method has to be done
You don't need javascript for doing so. Just delete the onClick and write the php Admin.php
file like this:
<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
{
$new = '{';
$new .= '"fullname":"' . $_GET['fullname'] . '",';
$new .= '"email":"' . $_GET['email'] . '",';
$new .= '"phone":"' . $_GET['phone'] . '",';
$new .= '}';
return $new;
}
function saveContact()
{
$datafile = fopen ("data/data.json", "a+");
if(!$datafile){
echo "<script>alert('Data not existed!')</script>";
}
else{
$contact_list = $contact_list . addNewContact();
file_put_contents("data/data.json", $contact_list);
}
fclose($datafile);
}
// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled
{ ?>
<form>
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact"/>
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->
Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...
Other thought, IE doesn't support placeholder.
It is totally possible, i did something similar based on the example of Mike Sav. That's the html page and ther shoul be an external test.js file in the same folder
example.html:
<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./test.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
document.getElementById('mylink').click();
}
</script>
</html>
test.js:
alert('hello world')
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0]
in jQuery you could do the following:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
`
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
Shortly: gene_name[x]
is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.
Further explanation:
Mutable objects are objects which value can be changed.
For example, list
is a mutable object, since you can append to it. int
is an immutable object, because you can't change it. When you do:
a = 5;
a = 3;
You don't change the value of a
, you create a new object and make a
point to its value.
Mutable objects cannot be hashed. See this answer.
To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple
, string
, int
.
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
Using foreach
loop without key
foreach($array as $item) {
echo $item['filename'];
echo $item['filepath'];
// to know what's in $item
echo '<pre>'; var_dump($item);
}
Using foreach
loop with key
foreach($array as $i => $item) {
echo $item[$i]['filename'];
echo $item[$i]['filepath'];
// $array[$i] is same as $item
}
Using for
loop
for ($i = 0; $i < count($array); $i++) {
echo $array[$i]['filename'];
echo $array[$i]['filepath'];
}
var_dump
is a really useful function to get a snapshot of an array or object.
def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
With PostgreSQL there is the ANY
or ALL
form:
WHERE col LIKE ANY( subselect )
or
WHERE col LIKE ALL( subselect )
where the subselect returns exactly one column of data.
pandas
versionsdf.index = df.index.rename('new name')
or
df.index.rename('new name', inplace=True)
The latter is required if a data frame should retain all its properties.
Assert by exception message:
try {
MyAgent.getNameByNode("d");
} catch (Exception e) {
Assert.assertEquals("Failed to fetch data.", e.getMessage());
}
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
This would get you the index of the clicked row, starting with one:
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
<tr>_x000D_
<td>1</td><td>1</td><td>1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td><td>2</td><td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td><td>3</td><td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you want to return the number stored in that first cell of each row:
$('#thetable').find('tr').click( function(){
var row = $(this).find('td:first').text();
alert('You clicked ' + row);
});
You module and class AthleteList
have the same name. Change:
import AthleteList
to:
from AthleteList import AthleteList
This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList
0123456789 is not a valid integer (usually zeros will be stripped)
I think something like this regexp would be better to use:
^[1-9]([0-9]*)$
(does not support signed numbers)
I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.
Use similar symbol: <del>र</del>
=> र
Try ₹
=> ₹
Use an image(bad solution but works): <img src="http://i.stack.imgur.com/nGbfO.png" width="8" height="10">
=>
Source: Empty rectanglar box is displayed instead of the rupee symbol in HTML
Here are three possibilities:
foo = """
this is
a multi-line string.
"""
def f1(foo=foo): return iter(foo.splitlines())
def f2(foo=foo):
retval = ''
for char in foo:
retval += char if not char == '\n' else ''
if char == '\n':
yield retval
retval = ''
if retval:
yield retval
def f3(foo=foo):
prevnl = -1
while True:
nextnl = foo.find('\n', prevnl + 1)
if nextnl < 0: break
yield foo[prevnl + 1:nextnl]
prevnl = nextnl
if __name__ == '__main__':
for f in f1, f2, f3:
print list(f())
Running this as the main script confirms the three functions are equivalent. With timeit
(and a * 100
for foo
to get substantial strings for more precise measurement):
$ python -mtimeit -s'import asp' 'list(asp.f3())'
1000 loops, best of 3: 370 usec per loop
$ python -mtimeit -s'import asp' 'list(asp.f2())'
1000 loops, best of 3: 1.36 msec per loop
$ python -mtimeit -s'import asp' 'list(asp.f1())'
10000 loops, best of 3: 61.5 usec per loop
Note we need the list()
call to ensure the iterators are traversed, not just built.
IOW, the naive implementation is so much faster it isn't even funny: 6 times faster than my attempt with find
calls, which in turn is 4 times faster than a lower-level approach.
Lessons to retain: measurement is always a good thing (but must be accurate); string methods like splitlines
are implemented in very fast ways; putting strings together by programming at a very low level (esp. by loops of +=
of very small pieces) can be quite slow.
Edit: added @Jacob's proposal, slightly modified to give the same results as the others (trailing blanks on a line are kept), i.e.:
from cStringIO import StringIO
def f4(foo=foo):
stri = StringIO(foo)
while True:
nl = stri.readline()
if nl != '':
yield nl.strip('\n')
else:
raise StopIteration
Measuring gives:
$ python -mtimeit -s'import asp' 'list(asp.f4())'
1000 loops, best of 3: 406 usec per loop
not quite as good as the .find
based approach -- still, worth keeping in mind because it might be less prone to small off-by-one bugs (any loop where you see occurrences of +1 and -1, like my f3
above, should automatically trigger off-by-one suspicions -- and so should many loops which lack such tweaks and should have them -- though I believe my code is also right since I was able to check its output with other functions').
But the split-based approach still rules.
An aside: possibly better style for f4
would be:
from cStringIO import StringIO
def f4(foo=foo):
stri = StringIO(foo)
while True:
nl = stri.readline()
if nl == '': break
yield nl.strip('\n')
at least, it's a bit less verbose. The need to strip trailing \n
s unfortunately prohibits the clearer and faster replacement of the while
loop with return iter(stri)
(the iter
part whereof is redundant in modern versions of Python, I believe since 2.3 or 2.4, but it's also innocuous). Maybe worth trying, also:
return itertools.imap(lambda s: s.strip('\n'), stri)
or variations thereof -- but I'm stopping here since it's pretty much a theoretical exercise wrt the strip
based, simplest and fastest, one.
Maybe someone will have the same issue as me:
I was in a element with display: flex
so I had to use flex-direction: column
.
Alternative:
var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]
It is possible to replace brackets with square or curly brackets if you need
There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.
Jeff Gilfelt's answer as a static helper method:
private static String getSizeName(Context context) {
int screenLayout = context.getResources().getConfiguration().screenLayout;
screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenLayout) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
return "small";
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return "normal";
case Configuration.SCREENLAYOUT_SIZE_LARGE:
return "large";
case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
return "xlarge";
default:
return "undefined";
}
}
Add reference Project->References Microsoft XML, 6.0 and you can use example code:
Dim xml As String
xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
Dim oXml As MSXML2.DOMDocument60
Set oXml = New MSXML2.DOMDocument60
oXml.loadXML xml
Dim oSeqNodes, oSeqNode As IXMLDOMNode
Set oSeqNodes = oXml.selectNodes("//root/person")
If oSeqNodes.length = 0 Then
'show some message
Else
For Each oSeqNode In oSeqNodes
Debug.Print oSeqNode.selectSingleNode("name").Text
Next
End If
be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text
I had a similar problem due to a zombie vim.exe process.
Killing it in Task Manager, followed by a git rebase --abort
fixed it.
Unfortunatelly, for IIS installed on Windows 7/8 machines, there is no option to create users only for IIS authentification. For Windows Server there is that option where you can add users from IIS Manager UI. These users have roles only on IIS, but not for the rest of the system. In this article it shows how you add users, but it is incorrect stating that is also appliable to standard OS, it only applies to server versions.
Swift 4
You can use Async Function for these situations. When you use DispatchGroup()
,Sometimes deadlock may be occures.
var a: Int?
@objc func myFunction(completion:@escaping (Bool) -> () ) {
DispatchQueue.main.async {
let b: Int = 3
a = b
completion(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
myFunction { (status) in
if status {
print(self.a!)
}
}
}
To show current language, you can use:
<?php echo $lang=get_bloginfo("language"); ?>
Plain and simple
In my case, I restarted my eclipse IDE without deleting/editing my workspace or .metadata folder. Error "An internal error occurred during: "Initializing Java Tooling". java.lang.NullPointerException" is gone and Eclipse just working good.
COALESCE
function same ISNULL
function
Note. you must use COALESCE
function with same data type of column that you check is null.
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
Solved by adding the following dependency into pom.xml file :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
If you don't encounter any permission errors with
pip install -U numpy
try:
pip install --user -U numpy
It's all about context, and also who is responsible for handling duplicates in requests (server or client or both)
If server just point the duplicate, look at 4xx:
For implicit handling of duplicates, look at 2XX:
if the server is expected to return something, look at 3XX:
when the server is able to point the existing resource, it implies a redirection.
If the above is not enough, it's always a good practice to prepare some error message in the body of the response.
Python has two different ways to convert an object to a string: str()
and repr()
. Printing an object uses str()
; printing a list containing an object uses str()
for the list itself, but the implementation of list.__str__()
calls repr()
for the individual items.
So you should also overwrite __repr__()
. A simple
__repr__ = __str__
at the end of the class body will do the trick.
Also can use without parent
say router definition like:
{path:'/about', name: 'About', component: AboutComponent}
then can navigate by name
instead of path
goToAboutPage() {
this.router.navigate(['About']); // here "About" is name not path
}
Updated for V2.3.0
In Routing from v2.0 name property no more exist. route define without name property. so you should use path instead of name. this.router.navigate(['/path'])
and no leading slash for path so use path: 'about'
instead of path: '/about'
router definition like:
{path:'about', component: AboutComponent}
then can navigate by path
goToAboutPage() {
this.router.navigate(['/about']); // here "About" is path
}
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
When user press F5 although new request goes to web server and get a responce for the request as well. But when the responce header is Parsed it check the required information in browser cache. If the required information in cache has not expired then that information is restored from in cache itself.
When user click on CTRL-F5 even then new request goes to web server and get a responce. But this time when the responce header is Parsed it do not check any required information in cache, and bring all updated information form server only.
Here is an example of SIGSEGV.
root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
int * p ;
* p = 0x1234;
return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c
root@pierr-desktop:/opt/playGround# ./test
Segmentation fault
And here is the detail.
How to handle it?
Avoid it as much as possible in the first place.
Program defensively: use assert(), check for NULL pointer , check for buffer overflow.
Use static analysis tools to examine your code.
compile your code with -Werror -Wall.
Has somebody review your code.
When that actually happened.
Examine you code carefully.
Check what you have changed since the last time you code run successfully without crash.
Hopefully, gdb will give you a call stack so that you know where the crash happened.
EDIT : sorry for a rush. It should be *p = 0x1234;
instead of p = 0x1234
;
In case you already use jquery-ui (specifically datepicker):
Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }
Usage:
var myDate = new Date();
myDate.getWeek();
More here: UI/Datepicker/iso8601Week
I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jquery-ui this might just be a simple fit for someone - as it was for me.
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
It looks like your psql doesn't run. You should run it before connect. You can do that using Postgres.app for Mac OS only. (Download and install this app http://postgresapp.com) Open the app, and you have a PostgreSQL server ready and awaiting new connections. Close the app, and the server shuts down. You also can find this info here http://www.postgresql.org/download/macosx/. Hope this will help you.
If you couldn't find the build.xml file in your project then you have to build it to be able to debug it and get your .apk
you can use this command-line to build:
android update project -p "project full path"
where "Project full path" -- Give your full path of your project location
after this you will find the build.xml then you can debug it.
Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool.
git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge
For those using something like babel stage-2 or transform-class-properties:
import React, { PropTypes, Component } from 'react';
export default class ExampleComponent extends Component {
static contextTypes = {
// some context types
};
static propTypes = {
prop1: PropTypes.object
};
static defaultProps = {
prop1: { foobar: 'foobar' }
};
...
}
Update
As of React v15.5, PropTypes
was moved out of the main React Package (link):
import PropTypes from 'prop-types';
Edit
As pointed out by @johndodo, static
class properties are actually not a part of the ES7 spec, but rather are currently only supported by babel. Updated to reflect that.
I have gone through many links but this answer helped me alot:
$scope.redirectPage = function (data) {
$window.open(data, "popup", "width=1000,height=700,left=300,top=200");
};
** data will be absolute url which you are hitting.
Use the below.
background-image: url("././images/image.png");
This shall work.
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id)
works as onClick
but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/
$('.moderate .button').on('click', (event) => {_x000D_
$(event.target).siblings('.dropdown')_x000D_
.toggleClass('is-open');_x000D_
});_x000D_
_x000D_
$(document).click(function(e) {_x000D_
$('.moderate')_x000D_
.not($('.moderate').has($(e.target)))_x000D_
.children('.dropdown')_x000D_
.removeClass('is-open');_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />_x000D_
_x000D_
<script_x000D_
src="https://code.jquery.com/jquery-3.2.1.min.js"_x000D_
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="_x000D_
crossorigin="anonymous"></script>_x000D_
_x000D_
<style>_x000D_
.dropdown {_x000D_
box-shadow: 0 0 2px #777;_x000D_
display: none;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
padding: 2px;_x000D_
z-index: 10;_x000D_
}_x000D_
_x000D_
.dropdown a {_x000D_
font-size: 12px;_x000D_
padding: 4px;_x000D_
}_x000D_
_x000D_
.dropdown.is-open {_x000D_
display: block;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a> </li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
<button class="button is-small" type="button">_x000D_
moderate_x000D_
</button>_x000D_
_x000D_
<div class="box dropdown">_x000D_
<ul>_x000D_
<li><a class="nav-item">edit</a></li>_x000D_
<li><a class="nav-item">delete</a></li>_x000D_
<li><a class="nav-item">block user</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
Here's what I ended up using.
I'm very new to AngularJS, so would love to see better / alternative solutions.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
Example usage:
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
You can also use PreviewKeyDown in WPF:
<TextBox PreviewKeyDown="EnterClicked" />
or in C#:
myTextBox.PreviewKeyDown += EnterClicked;
And then in the attached class:
void EnterClicked(object sender, KeyEventArgs e) {
if(e.Key == Key.Return) {
DoSomething();
e.Handled = true;
}
}
How about trying this:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
I'm able to modify a script variable value by assignment in the Console. Seems simplest.
Mostly, I prefer to use this syntax :
if ($('#MyId')!= null) {
// dostuff
}
Even if this code is not commented, the functionality is obvious.
I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.
C# Websocket server :
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
namespace WebSocketServer
{
class Program
{
static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static void Main(string[] args)
{
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
serverSocket.Listen(1); //just one socket
serverSocket.BeginAccept(null, 0, OnAccept, null);
Console.Read();
}
private static void OnAccept(IAsyncResult result)
{
byte[] buffer = new byte[1024];
try
{
Socket client = null;
string headerResponse = "";
if (serverSocket != null && serverSocket.IsBound)
{
client = serverSocket.EndAccept(result);
var i = client.Receive(buffer);
headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
// write received data to the console
Console.WriteLine(headerResponse);
Console.WriteLine("=====================");
}
if (client != null)
{
/* Handshaking and managing ClientSocket */
var key = headerResponse.Replace("ey:", "`")
.Split('`')[1] // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
.Replace("\r", "").Split('\n')[0] // dGhlIHNhbXBsZSBub25jZQ==
.Trim();
// key should now equal dGhlIHNhbXBsZSBub25jZQ==
var test1 = AcceptKey(ref key);
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + test1 + newLine + newLine
//+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
//+ "Sec-WebSocket-Version: 13" + newLine
;
client.Send(System.Text.Encoding.UTF8.GetBytes(response));
var i = client.Receive(buffer); // wait for client to send a message
string browserSent = GetDecodedData(buffer, i);
Console.WriteLine("BrowserSent: " + browserSent);
Console.WriteLine("=====================");
//now send message to client
client.Send(GetFrameFromString("This is message from server to client."));
System.Threading.Thread.Sleep(10000);//wait for message to be sent
}
}
catch (SocketException exception)
{
throw exception;
}
finally
{
if (serverSocket != null && serverSocket.IsBound)
{
serverSocket.BeginAccept(null, 0, OnAccept, null);
}
}
}
public static T[] SubArray<T>(T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
private static string AcceptKey(ref string key)
{
string longKey = key + guid;
byte[] hashBytes = ComputeHash(longKey);
return Convert.ToBase64String(hashBytes);
}
static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
private static byte[] ComputeHash(string str)
{
return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
}
//Needed to decode frame
public static string GetDecodedData(byte[] buffer, int length)
{
byte b = buffer[1];
int dataLength = 0;
int totalLength = 0;
int keyIndex = 0;
if (b - 128 <= 125)
{
dataLength = b - 128;
keyIndex = 2;
totalLength = dataLength + 6;
}
if (b - 128 == 126)
{
dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
keyIndex = 4;
totalLength = dataLength + 8;
}
if (b - 128 == 127)
{
dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
keyIndex = 10;
totalLength = dataLength + 14;
}
if (totalLength > length)
throw new Exception("The buffer length is small than the data length");
byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };
int dataIndex = keyIndex + 4;
int count = 0;
for (int i = dataIndex; i < totalLength; i++)
{
buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
count++;
}
return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
}
//function to create frames to send to client
/// <summary>
/// Enum for opcode types
/// </summary>
public enum EOpcodeType
{
/* Denotes a continuation code */
Fragment = 0,
/* Denotes a text code */
Text = 1,
/* Denotes a binary code */
Binary = 2,
/* Denotes a closed connection */
ClosedConnection = 8,
/* Denotes a ping*/
Ping = 9,
/* Denotes a pong */
Pong = 10
}
/// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
/// <param name="Message">The message to encode into the frame</param>
/// <param name="Opcode">The opcode of the frame</param>
/// <returns>Byte array in form of a websocket frame</returns>
public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
{
byte[] response;
byte[] bytesRaw = Encoding.Default.GetBytes(Message);
byte[] frame = new byte[10];
int indexStartRawData = -1;
int length = bytesRaw.Length;
frame[0] = (byte)(128 + (int)Opcode);
if (length <= 125)
{
frame[1] = (byte)length;
indexStartRawData = 2;
}
else if (length >= 126 && length <= 65535)
{
frame[1] = (byte)126;
frame[2] = (byte)((length >> 8) & 255);
frame[3] = (byte)(length & 255);
indexStartRawData = 4;
}
else
{
frame[1] = (byte)127;
frame[2] = (byte)((length >> 56) & 255);
frame[3] = (byte)((length >> 48) & 255);
frame[4] = (byte)((length >> 40) & 255);
frame[5] = (byte)((length >> 32) & 255);
frame[6] = (byte)((length >> 24) & 255);
frame[7] = (byte)((length >> 16) & 255);
frame[8] = (byte)((length >> 8) & 255);
frame[9] = (byte)(length & 255);
indexStartRawData = 10;
}
response = new byte[indexStartRawData + length];
int i, reponseIdx = 0;
//Add the frame bytes to the reponse
for (i = 0; i < indexStartRawData; i++)
{
response[reponseIdx] = frame[i];
reponseIdx++;
}
//Add the data bytes to the response
for (i = 0; i < length; i++)
{
response[reponseIdx] = bytesRaw[i];
reponseIdx++;
}
return response;
}
}
}
Client html and javascript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
socket.onopen = function() {_x000D_
// alert('handshake successfully established. May send data now...');_x000D_
socket.send("Hi there from browser.");_x000D_
};_x000D_
socket.onmessage = function (evt) {_x000D_
//alert("About to receive data");_x000D_
var received_msg = evt.data;_x000D_
alert("Message received = "+received_msg);_x000D_
};_x000D_
socket.onclose = function() {_x000D_
alert('connection closed');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
Update (2/14/2015) - I've rewritten the script a bit, to better handle the case of conflicts, which should now be presented as unmerged conflicts rather than .rej files.
I often find it more intuitive to do the inverse of @bukzor's approach. That is, to stage some changes, and then stash only those staged changes.
Unfortunately, git doesn't offer a git stash --only-index or similar, so I whipped up a script to do this.
#!/bin/sh
# first, go to the root of the git repo
cd `git rev-parse --show-toplevel`
# create a commit with only the stuff in staging
INDEXTREE=`git write-tree`
INDEXCOMMIT=`echo "" | git commit-tree $INDEXTREE -p HEAD`
# create a child commit with the changes in the working tree
git add -A
WORKINGTREE=`git write-tree`
WORKINGCOMMIT=`echo "" | git commit-tree $WORKINGTREE -p $INDEXCOMMIT`
# get back to a clean state with no changes, staged or otherwise
git reset -q --hard
# Cherry-pick the index changes back to the index, and stash.
# This cherry-pick is guaranteed to succeed
git cherry-pick -n $INDEXCOMMIT
git stash
# Now cherry-pick the working tree changes. This cherry-pick may fail
# due to conflicts
git cherry-pick -n $WORKINGCOMMIT
CONFLICTS=`git ls-files -u`
if test -z "$CONFLICTS"; then
# If there are no conflicts, it's safe to reset, so that
# any previously unstaged changes remain unstaged
#
# However, if there are conflicts, then we don't want to reset the files
# and lose the merge/conflict info.
git reset -q
fi
You can save the above script as git-stash-index
somewhere on your path, and can then invoke it as git stash-index
# <hack hack hack>
git add <files that you want to stash>
git stash-index
Now the stash contains a new entry that only contains the changes you had staged, and your working tree still contains any unstaged changes.
In some cases, the working tree changes may depend on the index changes, so when you stash the index changes, the working tree changes have a conflict. In this case, you'll get the usual unmerged conflicts that you can resolve with git merge/git mergetool/etc.
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
The expression $(document).ready(function() deprecated in jQuery3.
See working fiddle with jQuery 3 here
Take into account I didn't include the showless button.
Here's the code:
JS
$(function () {
x=3;
$('#myList li').slice(0, 3).show();
$('#loadMore').on('click', function (e) {
e.preventDefault();
x = x+5;
$('#myList li').slice(0, x).slideDown();
});
});
CSS
#myList li{display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
You could try setting the database to single user mode.
https://stackoverflow.com/a/11624/2408095
use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER
Simple solution
{{ orderTotal | number : '1.2-2'}}
//output like this
// public orderTotal = 220.45892221
// {{ orderTotal | number : '1.2-2'}}
// final Output
// 220.45
Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:
runas /user:(ComputerName)\(local admin) powershell.exe
So a basic example would be:
runas /user:MyLaptop\[email protected] powershell.exe
You can find more information on this subject in Runas.
However, you could also do one more thing :
then your system will execute the elevated powershell.
This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.
It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.
Read more in Scott Hanselman's blog post about it and other VS improvements here.
As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:
The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.
configure static ip on the raspberry pi:
sudo nano /etc/network/interfaces
and then add:
iface eth0 inet static
address 169.254.0.2
netmask 255.255.255.0
broadcast 169.254.0.255
then you can acces your raspberry via ssh
ssh [email protected]
In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.
Keystore is used by a server to store private keys, and Truststore is used by third party client to store public keys provided by server to access. I have done that in my production application. Below are the steps for generating java certificates for SSL communication:
keytool -genkey -keystore server.keystore -alias mycert -keyalg RSA -keysize 2048 -validity 3950
keytool -selfcert -alias mycert -keystore server.keystore -validity 3950
keytool -export -alias mycert -keystore server.keystore -rfc -file mycert.cer
keytool -importcert -alias mycert -file mycert.cer -keystore truststore
I am always using:
input.disabled {
pointer-events:none;
color:#AAA;
background:#F5F5F5;
}
and then applying the css class to the input field:
<input class="disabled" type="text" value="90" name="myinput" id="myinput" />
I made this generic state machine out of Juliet's code. It's working awesome for me.
These are the benefits:
TState
and TCommand
, TransitionResult<TState>
to have more control over the output results of [Try]GetNext()
methodsStateTransition
only through AddTransition(TState, TCommand, TState)
making it easier to work with itCode:
public class StateMachine<TState, TCommand>
where TState : struct, IConvertible, IComparable
where TCommand : struct, IConvertible, IComparable
{
protected class StateTransition<TS, TC>
where TS : struct, IConvertible, IComparable
where TC : struct, IConvertible, IComparable
{
readonly TS CurrentState;
readonly TC Command;
public StateTransition(TS currentState, TC command)
{
if (!typeof(TS).IsEnum || !typeof(TC).IsEnum)
{
throw new ArgumentException("TS,TC must be an enumerated type");
}
CurrentState = currentState;
Command = command;
}
public override int GetHashCode()
{
return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();
}
public override bool Equals(object obj)
{
StateTransition<TS, TC> other = obj as StateTransition<TS, TC>;
return other != null
&& this.CurrentState.CompareTo(other.CurrentState) == 0
&& this.Command.CompareTo(other.Command) == 0;
}
}
private Dictionary<StateTransition<TState, TCommand>, TState> transitions;
public TState CurrentState { get; private set; }
protected StateMachine(TState initialState)
{
if (!typeof(TState).IsEnum || !typeof(TCommand).IsEnum)
{
throw new ArgumentException("TState,TCommand must be an enumerated type");
}
CurrentState = initialState;
transitions = new Dictionary<StateTransition<TState, TCommand>, TState>();
}
/// <summary>
/// Defines a new transition inside this state machine
/// </summary>
/// <param name="start">source state</param>
/// <param name="command">transition condition</param>
/// <param name="end">destination state</param>
protected void AddTransition(TState start, TCommand command, TState end)
{
transitions.Add(new StateTransition<TState, TCommand>(start, command), end);
}
public TransitionResult<TState> TryGetNext(TCommand command)
{
StateTransition<TState, TCommand> transition = new StateTransition<TState, TCommand>(CurrentState, command);
TState nextState;
if (transitions.TryGetValue(transition, out nextState))
return new TransitionResult<TState>(nextState, true);
else
return new TransitionResult<TState>(CurrentState, false);
}
public TransitionResult<TState> MoveNext(TCommand command)
{
var result = TryGetNext(command);
if(result.IsValid)
{
//changes state
CurrentState = result.NewState;
}
return result;
}
}
This is the return type of TryGetNext method:
public struct TransitionResult<TState>
{
public TransitionResult(TState newState, bool isValid)
{
NewState = newState;
IsValid = isValid;
}
public TState NewState;
public bool IsValid;
}
This is how you can create a OnlineDiscountStateMachine
from the generic class:
Define an enum OnlineDiscountState
for its states and an enum OnlineDiscountCommand
for its commands.
Define a class OnlineDiscountStateMachine
derived from the generic class using those two enums
Derive the constructor from base(OnlineDiscountState.InitialState)
so that the initial state is set to OnlineDiscountState.InitialState
Use AddTransition
as many times as needed
public class OnlineDiscountStateMachine : StateMachine<OnlineDiscountState, OnlineDiscountCommand>
{
public OnlineDiscountStateMachine() : base(OnlineDiscountState.Disconnected)
{
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Connected);
AddTransition(OnlineDiscountState.Disconnected, OnlineDiscountCommand.Connect, OnlineDiscountState.Error_AuthenticationError);
AddTransition(OnlineDiscountState.Connected, OnlineDiscountCommand.Submit, OnlineDiscountState.WaitingForResponse);
AddTransition(OnlineDiscountState.WaitingForResponse, OnlineDiscountCommand.DataReceived, OnlineDiscountState.Disconnected);
}
}
use the derived state machine
odsm = new OnlineDiscountStateMachine();
public void Connect()
{
var result = odsm.TryGetNext(OnlineDiscountCommand.Connect);
//is result valid?
if (!result.IsValid)
//if this happens you need to add transitions to the state machine
//in this case result.NewState is the same as before
Console.WriteLine("cannot navigate from this state using OnlineDiscountCommand.Connect");
//the transition was successfull
//show messages for new states
else if(result.NewState == OnlineDiscountState.Error_AuthenticationError)
Console.WriteLine("invalid user/pass");
else if(result.NewState == OnlineDiscountState.Connected)
Console.WriteLine("Connected");
else
Console.WriteLine("not implemented transition result for " + result.NewState);
}
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);
i have just added (overflow:scroll;) in (div3) with fixed height.
see the fiddle:- http://jsfiddle.net/fMs67/10/
Try this:
#yourElementId
{
background: url(yourImageLocation.jpg) no-repeat center center;
width: 100px;
height: 100px;
}
Keep in mind that width
and height
will only work if your DOM element has layout (a block displayed element, like a div
or an img
). If it is not (a span, for example), add display: block;
to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.
That won't work in IE<9 though, however, you can make IEs support that using:
PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.
auto-alignment shortcut key Ctrl
+Shift
+F
to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions
Reflection is pretty "heavy"
Perhaps try this solution:
C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things
Method1: ADD_MONTHS
ADD_MONTHS(SYSDATE, -6)
Method 2: Interval
SYSDATE - interval '6' month
Note:
if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH')
would give that. And it expects a Date
datatype as input.
With the latest version of dotnet cli (2.1.400 or greater), you can just set this msbuild property $(EnvironmentName)
and publish tooling will take care of adding ASPNETCORE_ENVIRONMENT to the web.config with the environment name.
Also, XDT support is available starting 2.2.100-preview1.
Sample: https://github.com/vijayrkn/webconfigtransform/blob/master/README.md
Also, using the StringBuilder.AppendLine method.
Because build's version changed (most probably you modified the source code), so recompile the solution and run the application again, after then it will hit debug break point.
You must add it to entryComponents
, as specified in the docs.
@NgModule({
imports: [
// ...
],
entryComponents: [
DialogInvokingComponent,
DialogResultExampleDialog
],
declarations: [
DialogInvokingComponent,
DialogResultExampleDialog
],
// ...
})
Here is a full example for an app module file with a dialog defined as entryComponents
.
You should use such a loop, that most fully conforms to your needs. For example:
for(int i = 0; i < 10; i++)
{
print(i);
}
//or
int i = 0;
while(i < 10)
{
print(i);
i++;
}
Obviously, in such situation, "for" looks better, than "while". And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.
Sorry for my bad english).
As a representative of HiQPdf Software I believe the best solution is HiQPdf HTML to PDF converter for .NET. It contains the most advanced HTML5, CSS3, SVG and JavaScript rendering engine on market. There is also a free version of the HTML to PDF library which you can use to produce for free up to 3 PDF pages. The minimal C# code to produce a PDF as a byte[] from a HTML page is:
HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
// set PDF page size, orientation and margins
htmlToPdfConverter.Document.PageSize = PdfPageSize.A4;
htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
htmlToPdfConverter.Document.Margins = new PdfMargins(0);
// convert HTML to PDF
byte[] pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
You can find more detailed examples both for ASP.NET and MVC in HiQPdf HTML to PDF Converter examples repository.
You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()
):
entryList.forEach(e->e.setTempId(tempId));
List<Entry> updatedEntries = entryList.stream()
.map(e->entityManager.update(entry, entry.getId()))
.collect(toList());
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
You can use rownum :
SELECT * FROM table WHERE rownum > 10 and rownum <= 20
This is documented in the 'R Installation and Administration' manual that came with your installation.
On my Linux box:
R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"
[3] "/usr/lib/R/library"
R>
meaning that the default path is the first of these. You can override that via an argument to both install.packages()
(from inside R) or R CMD INSTALL
(outside R).
You can also override by setting the R_LIBS_USER variable.
Keep in mind if you are wanting to test this component you will want to inject the window. Use the @Inject() function to inject the window object by naming it using a string token like detailed in this duplicate
For those not using Windows the file to change is netbeans-8.0/etc/netbeans.conf
and the line(s) to change is:
netbeans_jdkhome="/usr/lib/jvm/java-8-oracle"
commenting out the old value and inserting the new value
Just ran into the same problem. Installing the .NET framework on the target machine solved the problem.
Better yet, make sure all required dependencies are present in the machine where the code will be running.
You have two issues in your code.. First you need reference to capture the element on click. Try adding another parameter to your function to reference this. Also active class is for li element initially while you are tryin to add it to "a" element in the function. try this..
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data('month',this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data('year',this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data('last60',this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data('last90',this)">90 Days</a></li>
</ul>
</div>
<script>
function Data(string,element)
{
//1. get some data from server according to month year etc.,
//2. unactive all the remaining li's and make the current clicked element active by adding "active" class to the element
$('.filter').removeClass('active');
$(element).parent().addClass('active') ;
}
</script>
sp_describe_first_result_set
will help to identify the datatypes of query by analyzing datatypes of first resultset of query
Was getting the same error in SourceTree,go to Tools>Options>Network and check Add proxy server configuration to Git/Mercurial if you had already set the proxy settings
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE table1 RENAME TO _table1_old;
CREATE TABLE table1 (
( column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
);
INSERT INTO table1 (column1, column2, ... column_n)
SELECT column1, column2, ... column_n
FROM _table1_old;
COMMIT;
PRAGMA foreign_keys=on;
For more info: https://www.techonthenet.com/sqlite/tables/alter_table.php
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location
service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location
helper methods. E.g. we ran $location.search(..., ...)
to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url()
if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.com/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/'
as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
I just wanted to chime in that I hit this after updating Android Studio components.
What worked for me was to open gradle-wrapper.properties and update the gradle version used. As of now for my projects the line reads:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
ARIA does not change functionality, it only changes the presented roles/properties to screen reader users. WebAIM’s WAVE toolbar identifies ARIA roles on the page.
Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
Log.d("KEY", iterator.next());
}
I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.
Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl
implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.
Change callSoapWebService
method first line to following.
SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();
I hope it will be helpful to others.
Looking at the source code of the page I took the reCaptcha part and changed the code a bit. Here's the code:
HTML:
<div class="tabs">
<ul class="product-tabs">
<li id="product_tabs_new" class="active"><a href="#">Detailed Description</a></li>
<li id="product_tabs_what"><a href="#">Request Information</a></li>
<li id="product_tabs_wha"><a href="#">Make Offer</a></li>
</ul>
</div>
<div class="tab_content">
<li class="wide">
<div id="product_tabs_new_contents">
<?php $_description = $this->getProduct()->getDescription(); ?>
<?php if ($_description): ?>
<div class="std">
<h2><?php echo $this->__('Details') ?></h2>
<?php echo $this->helper('catalog/output')->productAttribute($this->getProduct(), $_description, 'description') ?>
</div>
<?php endif; ?>
</div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="more_info_recaptcha_box" class="input-box more_info_recaptcha_box"></div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="make_offer_recaptcha_box" class="input-box make_offer_recaptcha_box"></div>
</li>
</div>
jQuery:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
var recapExist = false;
// Create our reCaptcha as needed
jQuery('#product_tabs_what').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
} else if(recapExist == 'more_info_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
}
});
jQuery('#product_tabs_wha').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
} else if(recapExist == 'make_offer_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way (I think :)
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
}
});
});
</script>
I am using here simple javascript tab functionality. So, didn't included that code.
When user would click on "Request Information" (#product_tabs_what)
then JS will check if recapExist
is false
or has some value. If it has a value then this will call Recaptcha.destroy();
to destroy the old loaded reCaptcha and will recreate it for this tab. Otherwise this will just create a reCaptcha and will place into the #more_info_recaptcha_box
div. Same as for "Make Offer" #product_tabs_wha
tab.
try this;
select gid
from `gd`
group by gid
having count(*) > 10
order by lastupdated desc
You'll need to use the FileSystem object and perform some logic on the resultant FileStatus objects to manually recurse into the subdirectories.
You can also apply a PathFilter to only return the xml files using the listStatus(Path, PathFilter) method
The hadoop FsShell class has examples of this for the hadoop fs -lsr command, which is a recursive ls - see the source, around line 590 (the recursive step is triggered on line 635)
For reference, the solution is:
UPDATE mysql.user SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
UPDATE mysql.db SET host = '10.0.0.%' WHERE host = 'internalfoo' AND user != 'root';
FLUSH PRIVILEGES;
If you're writing a bash script, call it by name:
#!/bin/bash
/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).
The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.
I'll give my input because it helps me understand what im doing.
To make an auto scrolling slide show that has a 3 second wait I did the following:
var isPlaying = true;
function autoPlay(playing){
var delayTime = 3000;
var timeIncrement = 3000;
if(playing){
for(var i=0; i<6; i++){//I have 6 images
setTimeout(nextImage, delayTime);
delayTime += timeIncrement;
}
isPlaying = false;
}else{
alert("auto play off");
}
}
autoPlay(isPlaying);
Remember that when executing setTimeout() like this; it will execute all time out functions as if they where executed at the same time assuming that in setTimeout(nextImage, delayTime);delay time is a static 3000 milliseconds.
What I did to account for this was add an extra 3000 milli/s after each for loop incrementation via delayTime += timeIncrement;
.
For those who care here is what my nextImage() looks like:
function nextImage(){
if(currentImg === 1){//change to img 2
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[1].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[1];
imgDescription.innerHTML = imgDescText[1];
currentImg = 2;
}
else if(currentImg === 2){//change to img 3
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[2].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[2];
imgDescription.innerHTML = imgDescText[2];
currentImg = 3;
}
else if(currentImg === 3){//change to img 4
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[3].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[3];
imgDescription.innerHTML = imgDescText[3];
currentImg = 4;
}
else if(currentImg === 4){//change to img 5
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[4].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[4];
imgDescription.innerHTML = imgDescText[4];
currentImg = 5;
}
else if(currentImg === 5){//change to img 6
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[5].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[5];
imgDescription.innerHTML = imgDescText[5];
currentImg = 6;
}
else if(currentImg === 6){//change to img 1
for(var i=0; i<6; i++){
images[i].style.zIndex = "0";
}
images[0].style.zIndex = "1";
imgNumber.innerHTML = imageNumber_Text[0];
imgDescription.innerHTML = imgDescText[0];
currentImg = 1;
}
}
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
try this
$('#div_id').animate({scrollTop:0}, '500', 'swing');
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count
will just query (totals)
C
will link the db.table to the names row you need this to index
LIKE
should be obvs
8
will call all references in DB 8 or less (not really needed but i like neatness)
Avoid appending strings using String + String etc, use StringBuilder instead.
String separator = System.getProperty( "line.separator" );
StringBuilder lines = new StringBuilder( line1 );
lines.append( separator );
lines.append( line2 );
lines.append( separator );
String result = lines.toString( );
With CMake it would just be
add_compile_definitions(_USE_MATH_DEFINES)
in CMakeLists.txt
.
You can get the "search" part of the location object - and then parse it out.
var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
You can right click on your project, then choose Properties
, on Debug
tab you should uncheck launch browser
checkbox.
I think if you check your manifest first if you wrote android:hardwareAccelerated="false"
you should make it true
to having shadow for the card
Like this answer here
The proper solution is to set environment variable R_LIBS_USER
to the value of the file path to your desired library folder as opposed to getting RStudio to recognize a Rprofile.site file.
To set environment variable R_LIBS_USER
in Windows, go to the Control Panel (System Properties -> Advanced system properties -> Environment Variables -> User Variables) to a desired value (the path to your library folder), e.g.
Variable name: R_LIBS_USER
Variable value: C:/software/Rpackages
If for some reason you do not have access to the control panel, you can try running rundll32 sysdm.cpl,EditEnvironmentVariables
from the command line on Windows and add the environment variable from there.
Setting R_LIBS_USER will ensure that the library shows up first in .libPaths() regardless of starting RStudio directly or by right-clicking an file and "Open With" to start RStudio.
The Rprofile solution can work if RStudio is always started by clicking the RStudio shortcut. In this case, setting the default working directory to the directory that houses your Rprofile will be sufficient. The Rprofile solution does not work when clicking on a file to start RStudio because that changes the working directory away from the default working directory.
I got this issue in a non-maven project, two depended jar each contained a slf4j. I solved by remove one depended jar, compile the project(which of course getting failure) then add the removed one back.
Do you have a lot of applications running when you are trying this? I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000. It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
There are multiple possible causes for this error:
1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input()
decorator
Your html file:
<body [x]="...">
Your class file:
export class YourComponentClass {
@Input()
x: string;
...
}
(make sure you also have the parentheses)
2) Make sure you registered your component/directive/pipe classes in NgModule:
@NgModule({
...
declarations: [
...,
YourComponentClass
],
...
})
See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.
3) Also happens if you have a typo in your angular directive. For example:
<div *ngif="...">
^^^^^
Instead of:
<div *ngIf="...">
This happens because under the hood angular converts the asterisk syntax to:
<div [ngIf]="...">
You can try
document.getElementById("textboxid").readOnly = true;
Its a common error which happens when we try to access a database which doesn't exist. So create the database using
CREATE DATABASE blog_development;
The error commonly occours when we have dropped the database using
DROP DATABASE blog_development;
and then try to access the database.
There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi
directory, it works px
based, and in the drawable-mdpi
works approximately as dp base (thanks to resample).
Example file for the original question (border-right:1px solid red;) is here:
Just place it to the drawable-nodpi
directory.
In eclipse,
.jrxml
file and select Open with JasperReports Book Editor
Design
tab for the .jrxml
file.Compile Report
icon.My implementation uses the svg element in html and I also made a generator for making the wave you want:
https://smooth.ie/blogs/news/svg-wavey-transitions-between-sections
<div style="height: 150px; overflow: hidden;">
<svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
<path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z" style="stroke: none;fill: #e1efe3;"></path>
</svg>
</div>
RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code and you can use different URLs, Headers and Params, in every Call.
Add multiple URLs in your application class like this :
class Application : Application() {
override fun onCreate() {
super.onCreate()
retrofitClient = RetrofitClient.instance
//api url
.setBaseUrl("https://reqres.in/")
//you can set multiple urls
// .setUrl("example","http://ngrok.io/api/")
//set timeouts
.setConnectionTimeout(4)
.setReadingTimeout(15)
//enable cache
.enableCaching(this)
//add Headers
.addHeader("Content-Type", "application/json")
.addHeader("client", "android")
.addHeader("language", Locale.getDefault().language)
.addHeader("os", android.os.Build.VERSION.RELEASE)
}
companion object {
lateinit var retrofitClient: RetrofitClient
}
}
And then use the URL you need in your call:
retrofitClient.Get<GetResponseModel>()
//set base url
.setBaseUrlKey("example")
//set path
.setPath("api/users/2")
//set url params Key-Value or HashMap
.setUrlParams("KEY","Value")
.setResponseHandler(GetResponseModel::class.java,
object : ResponseHandler<GetResponseModel>() {
override fun onSuccess(response: Response<GetResponseModel>) {
super.onSuccess(response)
//handle response
}
}).run(this)
For more information see the documentation
As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.
ShowPopUpForToDoList: function (id, apprId, tab) {
var snapShot = "isFromAlert";
if (tab != "Request")
snapShot = "isFromTodoList";
$.ajax({
type: "GET",
url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
data: { id: id, tab: tab },
async:false,
success: function (data) {
ActionForm.EditActionFormPopup(id, snapShot);
}
});
},
Here SetParamForToDoList
will be excecuted first after the function ActionForm.EditActionFormPopup
will fire.
Tables are odd elements. Unlike div
s they have special rules. Add cellspacing
and cellpadding
attributes, set to 0
, and it should fix the problem.
<table id="page" width="100%" border="0" cellspacing="0" cellpadding="0">
Code:
var fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");
fadeAnim.fromValue = firstImage;
fadeAnim.toValue = secondImage;
fadeAnim.duration = 0.8; //smoothest value
imageView.layer.addAnimation(fadeAnim, forKey: "contents");
imageView.image = secondImage;
Example:
Fun, More Verbose Solution: (Toggling on a tap)
let fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");
switch imageView.image {
case firstImage?:
fadeAnim.fromValue = firstImage;
fadeAnim.toValue = secondImage;
imageView.image = secondImage;
default:
fadeAnim.fromValue = secondImage;
fadeAnim.toValue = firstImage;
imageView.image = firstImage;
}
fadeAnim.duration = 0.8;
imageView.layer.addAnimation(fadeAnim, forKey: "contents");
Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!
pkill -9 -u `id -u username`
Note: if you want to be nice remove -9, but it will not kill all kinds of processes.
z-index
property enables you to take your control at front. the bigger number you set the upper your element you get.
position
property should be relative
because position of html-element
should be position relatively against other controls in all dimensions.
element.style {
position:relative;
z-index:1000; //change your number as per elements lies on your page.
}
If you are using PHP, the best way is to control it the .htaccess
, you need to put your files, images and videos under consideration in a separate folder/directory, and create a new .htaccess
file in this directory with the below:
RewriteEngine On
RewriteCond %{REQUEST_URI} \.(mp4|mp3|avi)$ [NC]
RewriteCond %{HTTP_REFERER} !^http://sample.com/.*$ [NC]
RewriteRule ^.* - [F,L]
The first line %{REQUEST_URI}
will prevent getting the file through the web browser or through curl
.
The second line %{HTTP_REFERER}
will prevent accessing the image/video using HTML tags <img>
or <video>
from any website except the exception !
you provide instead of http://sample.com/
which usually should be your website itself.
You can also have a look at my question and the accepted answer here for more tricks on the browser side.
None of these worked for me. I'm using Mac OS 10.10.5 and Workbench 6.3. What worked for me is Database->Migration Wizard... Flow the steps very carefully
I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:
public static class Extensions
{
public static int IndexOf<T>(
this IEnumerable<T> list,
Predicate<T> condition) {
int i = -1;
return list.Any(x => { i++; return condition(x); }) ? i : -1;
}
}
void Main()
{
TestGetsFirstItem();
TestGetsLastItem();
TestGetsMinusOneOnNotFound();
TestGetsMiddleItem();
TestGetsMinusOneOnEmptyList();
}
void TestGetsFirstItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("a"));
// Assert
if(index != 0)
{
throw new Exception("Index should be 0 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsLastItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("d"));
// Assert
if(index != 3)
{
throw new Exception("Index should be 3 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnNotFound()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnEmptyList()
{
// Arrange
var list = new string[] { };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMiddleItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d", "e" };
// Act
int index = list.IndexOf(item => item.Equals("c"));
// Assert
if(index != 2)
{
throw new Exception("Index should be 2 but is: " + index);
}
"Test Successful".Dump();
}
A)
String str = "a string";
int length = str.length( ); // length == 8
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29
edit
If you want to count the number of a specific type of characters in a String
, then a simple method is to iterate through the String
checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
where TestCase
can be isLetter( )
, isDigit( )
, etc.
Or if you just want to count everything but spaces, then do a check in the if
like temp != ' '
B)
String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29
how about this:
df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
out = np.argwhere(df.columns.isin(['apple', 'orange'])).ravel()
print(out)
[1 2]
this will work as well
require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');
The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF
, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022
.
As you can see, even in the StackOverflow font the two characters have different sizes.
The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.
The simple solution is to use a font in which both characters have similar sizes.
The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:
input[type="password"] {
font-family: caption;
}
uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{
if (r > 2) r = 0;
if (r == 0) value[i] = 0;
if (r == 1)value[i] = 0;
if (r == 2)value[i] = 255;
r++;
}
Please pay attention to the comments after the 2 lines.
.box1 {
display: block;
padding: 10px;
margin-bottom: 100px; /* SIMPLY SET THIS PROPERTY AS MUCH AS YOU WANT. This changes the space below box1 */
text-align: justify;
}
.box2 {
display: block;
padding: 10px;
text-align: justify;
margin-top: 100px; /* OR ADD THIS LINE AND SET YOUR PROPER SPACE as the space above box2 */
}
There is probably a way (or three) to do this... however, I see one issue with your goal: how do you know when all the files have been uploaded? To rephrase in a way that makes more sense... how do you know what "all" means? According to the documentation, init
gets called at the initialization of the Dropzone itself, and then you set up the complete
event handler to do something when each file that's uploaded is complete. But, what mechanism is the user given to allow the program to know when he's dropped all the files he's intended to drop? If you are assuming that he/she will do a batch drop (i.e., drop onto the Dropzone 2-whatever number of files, at once, in one drop action), then the following code could/possibly should work:
Dropzone.options.filedrop = {
maxFilesize: 4096,
init: function () {
var totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
});
this.on("removed file", function (file) {
totalFiles -= 1;
});
this.on("complete", function (file) {
completeFiles += 1;
if (completeFiles === totalFiles) {
doSomething();
}
});
}
};
Basically, you watch any time someone adds/removes files from the Dropzone, and keep a count in closure variables. Then, when each file download is complete, you increment the completeFiles
progress counter var, and see if it now equals the totalCount you'd been watching and updating as the user placed things in the Dropzone. (Note: never used the plug-in/JS lib., so this is best guess as to what you could do to get what you want.)
Use the DATE function:
SELECT DATE(orders.date_purchased) AS date
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
You can use datetime.date.today()
and convert the resulting datetime.date
object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
Using base graphics, we can use at =
to control box position , combined with boxwex =
for the width of the boxes. The 1st boxplot
statement creates a blank plot. Then add the 2 traces in the following two statements.
Note that in the following, we use df[,-1]
to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.
boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red",
boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue",
boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15
Some dummy data:
df <- data.frame(
id = c(rep("Good",200), rep("Bad", 200)),
F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
F2 = c(rnorm(200,7,1), rnorm(200,6,1)),
F3 = c(rnorm(200,6,2), rnorm(200,9,3)),
F4 = c(rnorm(200,12,3), rnorm(200,8,2)))
TCP guarantees (in-order) packet delivery. UDP doesn't.
TCP - used for traffic that you need all the data for. i.e HTML, pictures, etc. UDP - used for traffic that doesn't suffer much if a packet is dropped, i.e. video & voice streaming, some data channels of online games, etc.
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
Using something like selection.node().getBBox()
you get values like
{
height: 5,
width: 5,
y: 50,
x: 20
}
Use selection.node().getBoundingClientRect()