To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
I've improved Josh's answer. I've noticed that dig
only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.
The new script takes a -x
argument for expanded output and a -s NS
argument to choose a specific nameserver: dig -x example.com
#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""
while :; do case "$1" in
--) shift; break ;;
-x) EXTENDED=y; shift ;;
-s) NS="$2"; shift 2 ;;
*) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"
test "${NS:-}" || NS=$(dig +short SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"
if test "$EXTENDED"; then
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
wild_ips="${wild_ips%|}"
for sub in $COMMON_SUBDOMAINS; do
dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
done | cat #grep -vE "${wild_ips}"
dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi
Your target domain might refuse to send you information. This can work as a filter based on browser agent or any other header information. This is a defense against bots, crawlers or any unwanted applications.
It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup
wouldn't do that.
To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping
command.
OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).
Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog
For this you must first say for the browser that the user receive an error 403. For this you can use this code:
header("HTTP/1.1 403 Forbidden" );
Then, the script send "error, error, error, error, error.......", so you must stop it. You can use
exit;
With this two lines the server send an error and stop the script.
Don't forget : that emulate the error, but you must set it in a .htaccess file, with
ErrorDocument 403 /error403.php
For Netbeans 2020 September version. JDK 11
(Suggesting this for Gradle project only)
1. create libs
folder in src/main/java
folder of the project
2. copy past all library jars in there
3. open build.gradle in files
tab of project window in project's root
4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom'
)
5. and in dependencies
add next string:
apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'application'
description = 'testing netbeans'
mainClassName = 'uz.ManipulatorIkrom' //4th step
repositories {
jcenter()
}
dependencies {
implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step
}
6. save, clean-build and then run the app
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
it's easy with the id of the div container : (I didn't put the close button inside the <a>
because that's does work properly on all browser.
<div id="myDiv">
<button class="close" onclick="document.getElementById('myDiv').style.display='none'" >Close</button>
<a class="fragment" href="http://google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
As an alternative to the nested IFs, there's a way to use do
/while(false)
to break out anywhere:
function()
{
HRESULT error = S_OK;
do
{
if(!SUCCEEDED(Operation1()))
{
error = OPERATION1FAILED;
break;
}
if(!SUCCEEDED(Operation2()))
{
error = OPERATION2FAILED;
break;
}
if(!SUCCEEDED(Operation3()))
{
error = OPERATION3FAILED;
break;
}
if(!SUCCEEDED(Operation4()))
{
error = OPERATION4FAILED;
break;
}
} while (false);
return error;
}
That gets you one exit point, lets you have other nesting of operations, but still not a real deep structure. If you don't like the !SUCCEEDED you could always do FAILED whatever. This kind of thing also lets you add other code between any two other checks without having to re-indent anything.
If you were really crazy, that whole if
block could be macroized too. :D
#define BREAKIFFAILED(x,y) if (!SUCCEEDED((x))) { error = (Y); break; }
do
{
BREAKIFFAILED(Operation1(), OPERATION1FAILED)
BREAKIFFAILED(Operation2(), OPERATION2FAILED)
BREAKIFFAILED(Operation3(), OPERATION3FAILED)
BREAKIFFAILED(Operation4(), OPERATION4FAILED)
} while (false);
To see all commands that are being executed by the script, add the -x
flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr
somewhere.
An update, several years later
This answer is old, and R has moved on. Tweaking read.table
to run a bit faster has precious little benefit. Your options are:
Using vroom
from the tidyverse package vroom
for importing data from csv/tab-delimited files directly into an R tibble. See Hector's answer.
Using fread
in data.table
for importing data from csv/tab-delimited files directly into R. See mnel's answer.
Using read_table
in readr
(on CRAN from April 2015). This works much like fread
above. The readme in the link explains the difference between the two functions (readr
currently claims to be "1.5-2x slower" than data.table::fread
).
read.csv.raw
from iotools
provides a third option for quickly reading CSV files.
Trying to store as much data as you can in databases rather than flat files. (As well as being a better permanent storage medium, data is passed to and from R in a binary format, which is faster.) read.csv.sql
in the sqldf
package, as described in JD Long's answer, imports data into a temporary SQLite database and then reads it into R. See also: the RODBC
package, and the reverse depends section of the DBI
package page. MonetDB.R
gives you a data type that pretends to be a data frame but is really a MonetDB underneath, increasing performance. Import data with its monetdb.read.csv
function. dplyr
allows you to work directly with data stored in several types of database.
Storing data in binary formats can also be useful for improving performance. Use saveRDS
/readRDS
(see below), the h5
or rhdf5
packages for HDF5 format, or write_fst
/read_fst
from the fst
package.
The original answer
There are a couple of simple things to try, whether you use read.table or scan.
Set nrows
=the number of records in your data (nmax
in scan
).
Make sure that comment.char=""
to turn off interpretation of comments.
Explicitly define the classes of each column using colClasses
in read.table
.
Setting multi.line=FALSE
may also improve performance in scan.
If none of these thing work, then use one of the profiling packages to determine which lines are slowing things down. Perhaps you can write a cut down version of read.table
based on the results.
The other alternative is filtering your data before you read it into R.
Or, if the problem is that you have to read it in regularly, then use these methods to read the data in once, then save the data frame as a binary blob with save
saveRDS
, then next time you can retrieve it faster with load
readRDS
.
remember
is undefined … and the checked
property is a boolean not a number.
function validate(){
var remember = document.getElementById('remember');
if (remember.checked){
alert("checked") ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
Completely Transparent StatusBar and NavigationBar
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
transparentStatusAndNavigation();
}
private void transparentStatusAndNavigation() {
//make full transparent statusBar
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
getWindow().setNavigationBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(final int bits, boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true"
<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
<!-- empty or not depending your project -->
</Context>
For example for all users (Builtin\Users), this method works fine - enjoy.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/
Here I have created handle-destroy directive.
ctrl.directive('handleDestroy', function() {
return function(scope, tElement, attributes) {
scope.$on('$destroy', function() {
alert("In destroy of:" + scope.todo.text);
});
};
});
I hit this same issue trying to install Dashcast on Centos 7. The fix was adding -fPIC
at the end of each of the CFLAGS in the x264 Makefile. Then I had to run make distclean
for both x264 and ffmpeg and rebuild.
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]
or [JsonProperty]
.
There are predefined naming strategies like CamelCaseNamingStrategy
, but you can implement your own ones.
The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization
I believe you can use...
RESET QUERY CACHE;
...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...
FLUSH QUERY CACHE;
See the Query Cache Status and Maintenance section of the MySQL manual for more information.
You can also use Yapdi:
Basic usage:
import yapdi daemon = yapdi.Daemon() retcode = daemon.daemonize() # This would run in daemon mode; output is not visible if retcode == yapdi.OPERATION_SUCCESSFUL: print('Hello Daemon')
vec1[i] = vec2[i]
will set the value of vec1[i]
to the value of vec2[i]
. Nothing is inserted. Your second approach is almost correct. Instead of +i+1
you need just +i
v1.insert(v1.begin()+i, v2[i])
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
The answer is that java.sql.Timestamp
is a mess and should be avoided. Use java.time.LocalDateTime
instead.
So why is it a mess? From the java.sql.Timestamp
JavaDoc, a java.sql.Timestamp
is a "thin wrapper around java.util.Date
that allows the JDBC API to identify this as an SQL TIMESTAMP value". From the java.util.Date
JavaDoc, "the Date
class is intended to reflect coordinated universal time (UTC)". From the ISO SQL spec a TIMESTAMP WITHOUT TIME ZONE "is a data type that is datetime without time zone". TIMESTAMP is a short name for TIMESTAMP WITHOUT TIME ZONE. So a java.sql.Timestamp
"reflects" UTC while SQL TIMESTAMP is "without time zone".
Because java.sql.Timestamp
reflects UTC its methods apply conversions. This causes no end of confusion. From the SQL perspective it makes no sense to convert a SQL TIMESTAMP value to some other time zone as a TIMESTAMP has no time zone to convert from. What does it mean to convert 42 to Fahrenheit? It means nothing because 42 does not have temperature units. It's just a bare number. Similarly you can't convert a TIMESTAMP of 2020-07-22T10:38:00 to Americas/Los Angeles because 2020-07-22T10:30:00 is not in any time zone. It's not in UTC or GMT or anything else. It's a bare date time.
java.time.LocalDateTime
is also a bare date time. It does not have a time zone, exactly like SQL TIMESTAMP. None of its methods apply any kind of time zone conversion which makes its behavior much easier to predict and understand. So don't use java.sql.Timestamp
. Use java.time.LocalDateTime
.
LocalDateTime ldt = rs.getObject(col, LocalDateTime.class);
ps.setObject(param, ldt, JDBCType.TIMESTAMP);
If you want 8 bit representation of characters that used in many encoding, this may help you.
You must change variable targetEncoding to whatever encoding you want.
Encoding targetEncoding = Encoding.GetEncoding(874); // Your target encoding
Encoding utf8 = Encoding.UTF8;
var stringBytes = utf8.GetBytes(Name);
var stringTargetBytes = Encoding.Convert(utf8, targetEncoding, stringBytes);
var ascii8BitRepresentAsCsString = Encoding.GetEncoding("Latin1").GetString(stringTargetBytes);
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
If need to find nested in some dirs:
find / -type f -wholename "*dirname/filename"
Or connected dirs:
find / -type d -wholename "*foo/bar"
You can use retainAll method and get the intersection of your two sets.
In case anyone wants the answer of Dirk Vollmar in a C# switch statement:
case "doc": return "application/msword";
case "dot": return "application/msword";
case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
case "docm": return "application/vnd.ms-word.document.macroEnabled.12";
case "dotm": return "application/vnd.ms-word.template.macroEnabled.12";
case "xls": return "application/vnd.ms-excel";
case "xlt": return "application/vnd.ms-excel";
case "xla": return "application/vnd.ms-excel";
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
case "xlsm": return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "xltm": return "application/vnd.ms-excel.template.macroEnabled.12";
case "xlam": return "application/vnd.ms-excel.addin.macroEnabled.12";
case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
case "ppt": return "application/vnd.ms-powerpoint";
case "pot": return "application/vnd.ms-powerpoint";
case "pps": return "application/vnd.ms-powerpoint";
case "ppa": return "application/vnd.ms-powerpoint";
case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
case "ppam": return "application/vnd.ms-powerpoint.addin.macroEnabled.12";
case "pptm": return "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
case "potm": return "application/vnd.ms-powerpoint.template.macroEnabled.12";
case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
case "mdb": return "application/vnd.ms-access";
check your casing, the name is typically stored in upper case
SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;
The selected answer will work in everything except IE. I wrote a tutorial on how to make it work cross browser = http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html
Here is the function I wrote;
function playSomeSounds(soundPath)
{
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
document.all.sound.src = soundPath;
}
else
{
var snd = new Audio(soundPath); // buffers automatically when created
snd.play();
}
};
You also need to add the following tag to the html page:
<bgsound id="sound">
Finally you can call the function and simply pass through the path here:
playSomeSounds("sounds/welcome.wav");
Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}
Reference:
If your merge commit is commit 0e1329e5, as above, you can get the diff that was contained in this merge by:
git diff 0e1329e5^..0e1329e5
I hope this helps!
I think the error because the elements are undefined ,so you need to add window.onload
event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
AND
between ORDER BY
and LIMIT
=
between ORDER BY
, LIMIT
keywords and conditionSo you query will look like:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
To start a container and set it to restart automatically on system reboot use
docker run -d --restart unless-stopped ecstatic_ritchie
Where ecstatic_ritchie
is an example name specifying the container in interest. Use docker ps -a
to list all container names.
To make particular running containers start automatically on system reboot
docker update --restart unless-stopped ecstatic_ritchie
To make all running containers start automatically on system reboot
docker update --restart unless-stopped $(docker ps -q)
See more on Docker homepage
in Notepad++v6.1.8 (Unicode) it works after removing the QuickText plugin.
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
The straight answer is already in a duplicate question: Why does the jquery change event not trigger when I set the value of a select using val()?
As you probably know setting the value of the select doesn't trigger the change() event, if you're looking for an event that is fired when an element's value has been changed through JS there isn't one.
If you really want to do this I guess the only way is to write a function that checks the DOM on an interval and tracks changed values, but definitely don't do this unless you must (not sure why you ever would need to)
Added this solution:
Another possible solution would be to create your own .val()
wrapper function and have it trigger a custom event after setting the value through .val()
, then when you use your .val() wrapper to set the value of a <select>
it will trigger your custom event which you can trap and handle.
Be sure to return this
, so it is chainable in jQuery fashion
My underlying APIs were all using cents to represent money, and I didn't want to change that. Nor was I working with large amounts of money. So I just put this in a helper method:
sprintf("%03d", amount).insert(-3, ".")
That converts the integer to a string with at least three digits (adding leading zeroes if necessary), then inserts a decimal point before the last two digits, never using a Float
. From there you can add whatever currency symbols are appropriate for your use case.
It's definitely quick and dirty, but sometimes that's just fine!
import java.util.*; public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C= new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for(int i =0 ; i< B.length ; i++) {
for(int j = 0 ; j<B.length;j++) {
B[i][j] = s.nextInt();
}
}
if(Cola==Rowb) {
for(int i = 0;i < A.length;i++){
for(int j = 0;j < A.length;j++){
C[i][j]=0;
for(int k = 0;k < B.length;k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
*/
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(C[i][j]+ "\t");
}
System.out.println();
}
}
}
In case of Mac OSX,
Go to Targets -> Build Phases click + to Copy new files build phases Select product directory and drop the file there.
Clean and run the project.
1. Put the jar (in my case,
gson-2.2.4.jar
) into the libs folder.2. Ensure that compile files (
libs/gson-2.2.4.jar
) is in your build.gradle file.3. Now Click on the "Sync Project with Gradle files"(Left to AVD manager Button on the topbar).
After I did the above three, it started working fine.
Location of JRE in Ubuntu:
/usr/lib/jvm/java-7-oracle/jre
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsUnchecked all Device orientation and checked only "Requires full screen". Its working properly
If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.
stages {
stage('Nginx') {
when { changeset "nginx/*"}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
}
}
You can combine multiple conditions using anyOf
or allOf
keywords for OR or AND behaviour accordingly:
when {
anyOf {
changeset "nginx/**"
changeset "fluent-bit/**"
}
}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
I've heard about having to use BackgroundImage because in future you are supposed to not be able to nest the Image tag. But I could not get BackgroudImage to properly display my background. What I did was nest my Image inside a View tag and style both the outer View as well as the image. Keys were setting width to null, and setting resizeMode to 'stretch'. Below is my code:
import React, {Component} from 'react';_x000D_
import { View, Text, StyleSheet, Image} from 'react-native';_x000D_
_x000D_
export default class BasicImage extends Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
_x000D_
this.state = {};_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<View style={styles.container}>_x000D_
<Image _x000D_
source={this.props.source}_x000D_
style={styles.backgroundImage}_x000D_
/>_x000D_
</View>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
const styles = StyleSheet.create({ _x000D_
container: {_x000D_
flex: 1,_x000D_
width: null,_x000D_
height: null,_x000D_
marginBottom: 50_x000D_
},_x000D_
text: {_x000D_
marginLeft: 5,_x000D_
marginTop: 22,_x000D_
fontFamily: 'fontawesome',_x000D_
color: 'black',_x000D_
fontSize: 25,_x000D_
backgroundColor: 'rgba(0,0,0,0)',_x000D_
},_x000D_
backgroundImage: {_x000D_
flex: 1,_x000D_
width: null,_x000D_
height: null,_x000D_
resizeMode: 'stretch',_x000D_
}_x000D_
});
_x000D_
Somewhere in your project, typically main.js or router.js
import Router from 'vue-router'
Router.prototype.open = function (routeObject) {
const {href} = this.resolve(routeObject)
window.open(href, '_blank')
}
In your component:
<div @click="$router.open({name: 'User', params: {ID: 123}})">Open in new tab</div>
#include <sstream> std::ostringstream s; s << "John " << age; std::string query(s.str());
std::string query("John " + std::to_string(age));
#include <boost/lexical_cast.hpp> std::string query("John " + boost::lexical_cast<std::string>(age));
Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.
select * from table
where tester NOT LIKE '%username%';
I moved my home directory from one mac to another (Mountain Lion to Yosemite) and didn't realize about the broken virtualenv until I lost hold of the old laptop. I had the virtualenv point to Python 2.7 installed by brew
and since Yosemite came with Python 2.7, I wanted to update my virtualenv to the system python. When I ran virtualenv
on top of the existing directory, I was getting OSError: [Errno 17] File exists: '/Users/hdara/bin/python2.7/lib/python2.7/config'
error. By trial and error, I worked around this issue by removing a few links and fixing up a few more manually. This is what I finally did (similar to what @Rockalite did, but simpler):
cd <virtualenv-root>
rm lib/python2.7/config
rm lib/python2.7/lib-dynload
rm include/python2.7
rm .Python
cd lib/python2.7
gfind . -type l -xtype l | while read f; do ln -s -f /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/${f#./} $f; done
After this, I was able to just run virtualenv on top of the existing directory.
You can use os.sep:
>>> import os
>>> os.sep
'/'
Whenever gcc
on the compilation machine and gdb
on the testing machine have differing versions, you may be facing debuginfo format incompatibility.
To fix that, try downgrading the debuginfo format:
gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...
Or match gdb
to the gcc
you're using.
In SSMS, set the database to read-only then back. The connections will be closed, which frees up the locks.
In my case there was a website that had open connections to the database. This method was easy enough:
Database Read-Only
to TrueSomething like this should work: From Frans Bouma's Blog
SELECT * FROM
(
SELECT a.*, rownum r__
FROM
(
SELECT * FROM ORDERS WHERE CustomerID LIKE 'A%'
ORDER BY OrderDate DESC, ShippingDate DESC
) a
WHERE rownum < ((pageNumber * pageSize) + 1 )
)
WHERE r__ >= (((pageNumber-1) * pageSize) + 1)
We can simply declare more than one Controller in the same module. Here's an example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<title> New Page </title>
</head>
<body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect -->
<h2> Books </h2>
<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
Enter book name: <input type = "text" ng-model = "book.name"><br>
Enter book category: <input type = "text" ng-model = "book.category"><br>
Enter book price: <input type = "text" ng-model = "book.price"><br>
Enter book author: <input type = "text" ng-model = "book.author"><br>
You are entering book: {{book.bookDetails()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('bookController', function($scope) {
$scope.book = {
name: "",
category: "",
price:"",
author: "",
bookDetails: function() {
var bookObject;
bookObject = $scope.book;
return "Book name: " + bookObject.name + '\n' + "Book category: " + bookObject.category + " \n" + "Book price: " + bookObject.price + " \n" + "Book Author: " + bookObject.author;
}
};
});
</script>
<h2> Albums </h2>
<input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
Enter Album name: <input type = "text" ng-model = "album.name"><br>
Enter Album category: <input type = "text" ng-model = "album.category"><br>
Enter Album price: <input type = "text" ng-model = "album.price"><br>
Enter Album singer: <input type = "text" ng-model = "album.singer"><br>
You are entering Album: {{album.albumDetails()}}
</div>
<script>
//no need to declare this again ;)
//var mainApp = angular.module("mainApp", []);
mainApp.controller('albumController', function($scope) {
$scope.album = {
name: "",
category: "",
price:"",
singer: "",
albumDetails: function() {
var albumObject;
albumObject = $scope.album;
return "Album name: " + albumObject.name + '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;
}
};
});
</script>
</body>
</html>
there is no built-in feature to check that - what you would do is write your own tld function which takes a list and an item, and calls the list's contains() method. e.g.
//in your own WEB-INF/custom-functions.tld file add this
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0"
>
<tlib-version>1.0</tlib-version>
<function>
<name>contains</name>
<function-class>com.Yourclass</function-class>
<function-signature>boolean contains(java.util.List,java.lang.Object)
</function-signature>
</function>
</taglib>
Then create a class called Yourclass, and add a static method called contains with the above signature. I m sure the implementation of that method is pretty self explanatory:
package com; // just to illustrate how to represent the package in the tld
public class Yourclass {
public static boolean contains(List list, Object o) {
return list.contains(o);
}
}
Then you can use it in your jsp:
<%@ taglib uri="/WEB-INF/custom-functions.tld" prefix="fn" %>
<c:if test="${ fn:contains( mylist, myValue ) }">style='display:none;'</c:if>
The tag can be used from any JSP in the site.
edit: more info regarding the tld file - more info here
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
Just use.
<![CDATA[ your text here ]]>
This will allow any characters except the ending
]]>
So you can include characters that would be illegal such as & and >. For example.
<element><![CDATA[ characters such as & and > are allowed ]]></element>
However, attributes will need to be escaped as CDATA blocks can not be used for them.
the new versions of mysql-connector establish SSL connection by default ...to solve it:
Download the older version of mysql-connector such as mysql-connector-java-5.0.8.zip
. . or . . Download OpenSSL for Windows and follow the instructions how to set it
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(image, 1.0 ); //you can use PNG too
[imageData writeToFile:@"image1.jpeg" atomically:YES];
If the default value of
string
were the empty string, I would not have to test
Wrong! Changing the default value doesn't change the fact that it's a reference type and someone can still explicitly set the reference to be null
.
Additionally
Nullable<String>
would make sense.
True point. It would make more sense to not allow null
for any reference types, instead requiring Nullable<TheRefType>
for that feature.
So why did the designers of C# choose to use
null
as the default value of strings?
Consistency with other reference types. Now, why allow null
in reference types at all? Probably so that it feels like C, even though this is a questionable design decision in a language that also provides Nullable
.
$('input:checked').map(function(i, e) {return e.value}).toArray();
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
I know the purists will hate this method, but you can cat
the file.
NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
These are the steps to follow when you want your PHP application to be installed on a LAN server (not on web)
Note: If firewall is installed, ensure that you add the http port 80 and 8080 to exceptions and allow to listen. Go to Control Panel>Windows Firewall>Allow a program to communicate through windows firewall>Add another program Name: http Port: 80 Add one more as http - 8080
If IIS (Microsoft .Net Application Internet Information Server) is installed with any Microsoft .Net application already on server, then it would have already occupied 80 port. In that case change the #Listen 192.168.1.193:80 to #Listen 192.168.1.193:8080
Hope this helps! :)
Add these two lines under dependencies
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
then
useLibrary 'org.apache.http.legacy'
under the android
I know it's too late but I had the same problem last week. None of the answers helped me. I then was playing around with the code and this worked, since I already added the fragments.
In your Activity, set an OnPageChangeListener
for the ViewPager
so that you will know when the user is in the second activity. If he is in the second activity, make a boolean true
as follows:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(0);
mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
mSectionsPagerAdapter.instantiateItem(mViewPager, position);
if(position == 1)
inAnalytics = true;
else if(position == 0)
inAnalytics = false;
}
@Override
public void onPageScrolled(int position, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Now check for the boolean whenever back button is pressed and set the current item to your first Fragment:
@Override
public void onBackPressed() {
if(inAnalytics)
mViewPager.setCurrentItem(0, true);
else
super.onBackPressed();
}
Try to use this command in your git repository root folder:
rm .git/logs/refs/remotes/origin/master
Popen expect a list of strings for non-shell calls and a string for shell calls.
Call subprocess.Popen with shell=True:
process = subprocess.Popen(command, stdout=tempFile, shell=True)
Hopefully this solves your issue.
This issue is listed here: https://bugs.python.org/issue17023
input{
text-align:center;
}
is all you need.
Working example in FF6. This method doesn't seem to be cross-browser compatible.
Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".
It will group by first field in the select clause
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+
<img src="'../images/foo.gif'"
alt="line 1
line 2" title="line 1
line 2">
Try a JavaScript tooltip library for a better result, something like OverLib.
You can use the DefaultView.ToTable method of a DataTable to do the filtering like this (adapt to C#):
Public Sub RemoveDuplicateRows(ByRef rDataTable As DataTable)
Dim pNewDataTable As DataTable
Dim pCurrentRowCopy As DataRow
Dim pColumnList As New List(Of String)
Dim pColumn As DataColumn
'Build column list
For Each pColumn In rDataTable.Columns
pColumnList.Add(pColumn.ColumnName)
Next
'Filter by all columns
pNewDataTable = rDataTable.DefaultView.ToTable(True, pColumnList.ToArray)
rDataTable = rDataTable.Clone
'Import rows into original table structure
For Each pCurrentRowCopy In pNewDataTable.Rows
rDataTable.ImportRow(pCurrentRowCopy)
Next
End Sub
You can try this :
unzip -v /your/jar.jar
This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class
Very easy with the dateTime() object, too.
$tomorrow = new DateTime('tomorrow');
echo $tomorrow->format("Y-m-d"); // Tomorrow's date
$yesterday = new DateTime('yesterday');
echo $yesterday->format("Y-m-d"); // Yesterday's date
Make sure your database myAttribute field contains null instead of zero.
function isNumber(value: string | number): boolean
{
return ((value != null) &&
(value !== '') &&
!isNaN(Number(value.toString())));
}
brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.
Here's a one-liner I've been using:
@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
echo main code here
pause
Notes:
This solution is written in PHP, but it should be easily adapted to other languages.
The original .htaccess
regex can cause problems with files like json-1.3.js
. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)
First, we use the following rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
Now, we write the following PHP function:
/**
* Given a file, i.e. /css/base.css, replaces it with a string containing the
* file's mtime, i.e. /css/base.1221534296.css.
*
* @param $file The file to be loaded. Must be an absolute path (i.e.
* starting with slash).
*/
function auto_version($file)
{
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
return $file;
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
Now, wherever you include your CSS, change it from this:
<link rel="stylesheet" href="/css/base.css" type="text/css" />
To this:
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />
This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.
This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.
All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
The right way to do this is use git-remote-dropbox: https://github.com/anishathalye/git-remote-dropbox
Creating your own bare repo in Dropbox causes a lot of problems. Anish (the creator of the library) explains it best:
The root cause of these problems is that the Dropbox desktop client is designed for syncing files, not Git repositories. Without special handling for Git repositories, it doesn’t maintain the same guarantees as Git. Operations on the remote repository are no longer atomic, and concurrent operations or unlucky timing with synchronization can result in a corrupted repository.
Traditional Git remotes run code on the server side to make this work properly, but we can’t do that.
Solution: It is possible to solve this properly. It is possible to use Git with Dropbox and have the same safety and consistency guarantees as a traditional Git remote, even when there are multiple users and concurrent operations!
For a user, it’s as simple as using git-remote-dropbox, a Git remote helper that acts as a transparent bidirectional bridge between Git and Dropbox and maintains all the guarantees of a traditional Git remote. It’s even safe to use with shared folders, so it can be used for collaboration (yay unlimited private repos with unlimited collaborators!).
With the remote helper, it’s possible to use Dropbox as a Git remote and continue using all the regular Git commands like git clone, git pull, and git push, and everything will just work as expected.
AWS added a new feature to connect to instance without any open port, the AWS SSM Session Manager. https://aws.amazon.com/blogs/aws/new-session-manager/
I've created a neat SSH ProxyCommand script that temporary adds your public ssh key to target instance during connection to target instance. The nice thing about this is you will connect without the need to add the ssh(22) port to your security groups, because the ssh connection is tunneled through ssm session manager.
AWS SSM SSH ProxyComand -> https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1
you need to take out the quotes:
soda = a + b
(You want to refer to the variables a
and b
, not the strings "a" and "b")
It seems that you can use the repository browser. Click the revision button at top-right and change it to the revision you want. Then right-click your file in the browser and use 'Copy to working copy...' but change the filename it will check out, to avoid a clash.
I find * useful when writing a function that takes another callback function as a parameter:
def some_function(parm1, parm2, callback, *callback_args):
a = 1
b = 2
...
callback(a, b, *callback_args)
...
That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. The nice thing is that the callback function can use normal function parameters. That is, it doesn't need to use the * syntax at all. Here's an example:
def my_callback_function(a, b, x, y, z):
...
x = 5
y = 6
z = 7
some_function('parm1', 'parm2', my_callback_function, x, y, z)
Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function().
Agree with iLoveTux , applying too many things (many colors and backgrounds) nothing worked , but here's what started working, Apply these properties to its css:
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance:none;
and then css styling started working on checkbox :)
DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
ArrayList files = new ArrayList();
foreach (string ext in exts)
files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());
There seem to be many things that cause this. For me it was a lowercase rewrite rule in IIS. Changed the problem files (js and png) to lowercase and problem went away.
if you use one line folder or file
chmod 755 $(find /yourfolder -type d)
chmod 644 $(find /yourfolder -type f)
I got my code for the answer from a book called "C++ Programming In Easy Steps". The could below should work.
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ofstream writer("filename.file-extension" , ios::app);
if (!writer)
{
cout << "Error Opening File" << endl;
return -1;
}
string info = "insert text here";
writer.append(info);
writer << info << endl;
writer.close;
return 0;
}
I hope this helps you.
While other answers already fulfilled the question (it's a 3 years old question after all), I'm just gonna add some info, and probably fixed a bit of misunderstanding.
Em, while originally meant as the term for a single 'M' character's width in typography, in digital medium it was shifted to a unit relative to the point size of the typeface (font-size or textSize), in other words it's uses the height of the text, not the width of a single 'M'.
In Android, that means when you specify the ems of a TextView, it uses the said TextView's textSize as the base, excluding the added padding for accents/diacritics. When you set a 16sp TextView's ems to 4, it means its width will be 64sp wide, thus explained @stefan 's comment about why a 10 ems wide EditText is able to fit 17 'M'.
You can do it like:
val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
println("empty df ")
else
println("normal df")
For any users having the same issue in 2017, I solved it the following way:
NavBar.contextTypes = {
router: React.PropTypes.object,
location: React.PropTypes.object
}
and use it like this:
componentDidMount () {
console.log(this.context.location.pathname);
}
You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins
change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1
This will explain it, I think...
import java.io.*;
class reading
{
public static void main(String args[]) throws IOException
{
float number;
System.out.println("Enter a number");
try
{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
String a = br.readLine();
number = Float.valueOf(a);
int x = (int)number;
System.out.println("Your input=" + number);
System.out.println("Your input in integer terms is = " + x);
}
catch(Exception e){
}
}
}
I would suggest using
SELECT * from table where field1 in
(
select distinct field1 from table
)
this way if you have the same value in field1 across multiple rows, all the records will be returned.
There is an operator missing, likely a *
:
-3.7 need_something_here (prof[x])
The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7
(a float) as a function, which is not allowed.
The parenthesis are also not needed in this case, the following may be sufficient/correct:
-3.7 * prof[x]
As Legolas points out, there are other things which may need to be addressed:
2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
^-- op missing
extra parenthesis --^
valid but questionable float*tuple --^
expression yields 0.0 always --^
You can use native element divider.
Install it with:
npm install --save react-native-elements
# or with yarn
yarn add react-native-elements
import { Divider } from 'react-native-elements'
Then go with:
<Divider style={{ backgroundColor: 'blue' }} />
You have to use
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>
?autoplay=1
and not
&autoplay=1
its the first URL param so its added with a ?
It's quite possible to do this in JavaScript as long as your fallback is another applink. Building on Nathan's suggestion:
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h2><a id="applink1" href="fb://profile/116201417">open facebook with fallback to appstore</a></h2>
<h2><a id="applink2" href="unknown://nowhere">open unknown with fallback to appstore</a></h2>
<p><i>Only works on iPhone!</i></p>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
function applink(fail){
return function(){
var clickedAt = +new Date;
// During tests on 3g/3gs this timeout fires immediately if less than 500ms.
setTimeout(function(){
// To avoid failing on return to MobileSafari, ensure freshness!
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink1").onclick = applink(appstorefail);
document.getElementById("applink2").onclick = applink(appstorefail);
</script>
</body>
</html>
Implicit cursor returns only one record and are called automatically. However, explicit cursors are called manually and can return more than one record.
you can enter the jdk path required as th full path for java.exe in sql developer for oracle 11g.
I found the jdk at the following path in my system.
c:\app\sony\product\11.0.0\db_1\jdk
I had a similar problem recently, and here's what I did:
SELECT
columnname as 'Original_Value',
LEN(LTRIM(columnname)) as 'Orig_Val_Char_Count',
N'['+columnname+']' as 'UnicodeStr_Value',
LEN(N'['+columnname+']')-2 as 'True_Char_Count'
FROM mytable
The first two columns look at the original value and count the characters (minus leading/trailing spaces).
I needed to compare that with the true count of characters, which is why I used the second LEN function. It sets the column value to a string, forces that string to Unicode, and then counts the characters.
By using the brackets, you ensure that any leading or trailing spaces are also counted as characters; of course, you don't want to count the brackets themselves, so you subtract 2 at the end.
How to echo key and value of an array without and with loop
$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];
I had a project with the same problem , I solved it with change dotnet core version from 2.2 to 2.0, If your problem has remained , Try this solution
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
The <p>
paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p>
tag incorrectly. Perhaps the <span>
tag more closely fits what you want to achieve...?
The difference is that non-constant pointer variable(not to be confused with a pointer to constant) may be changed at some time during program execution, requires pointer semantics to be used(&,*) operators, while references can be set upon initialization only(that's why you can set them in constructor initializer list only, but not somehow else) and use ordinary value accessing semantics. Basically references were introduced to allow support for operators overloading as I had read in some very old book. As somebody stated in this thread - pointer can be set to 0 or whatever value you want. 0(NULL, nullptr) means that the pointer is initialized with nothing. It is an error to dereference null pointer. But actually the pointer may contain a value that doesn't point to some correct memory location. References in their turn try not to allow a user to initialize a reference to something that cannot be referenced due to the fact that you always provide rvalue of correct type to it. Although there are a lot of ways to make reference variable be initialized to a wrong memory location - it is better for you not to dig this deep into details. On machine level both pointer and reference work uniformly - via pointers. Let's say in essential references are syntactic sugar. rvalue references are different to this - they are naturally stack/heap objects.
You can search for "Anaconda prompt" in installed programs and run it.
When it opens, it shows the directory anaconda is working from.
As you can see c:\programdata\anaconda2 is my installed directory.
*side note: programdata folder is hidden in windows so you'll have to enter its path in the folder explorer to access it.
[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to %@ was %0.02f",QString1,QString2,M1]];
[averagRatioArray addObject:[NSString stringWithFormat:@"When you respond No to %@ the average response to %@ was %0.02f",QString1,QString2,M0]];
UIFont *font2 = [UIFont fontWithName:@"Helvetica-Bold" size:15];
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
NSMutableAttributedString *str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"When you respond Yes to %@ the average response to %@ was",QString1,QString2]];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0,[@"When you respond Yes to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@"When you respond Yes to " length],[QString1 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString1 length],[@" the average response to " length])];
[str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange([@" the average response to " length],[QString2 length])];
[str addAttribute:NSFontAttributeName value:font range:NSMakeRange([QString2 length] ,[@" was" length])];
// [str addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(49+[QString1 length]+[QString2 length] ,8)];
[averagRatioArray addObject:[NSString stringWithFormat:@"%@",str]];
First you to add a class then remove id
<script type="text/javascript">
$(document).ready(function(){
$("#page_navigation1").addClass("page_navigation");
$("#add").click(function(){
$(".page_navigation").attr("id","page_navigation1");
});
$("#remove").click(function(){
$(".page_navigation").removeAttr("id");
});
});
</script>
The tools sed
or tr
will do this for you by swapping the whitespace for nothing
sed 's/ //g'
tr -d ' '
Example:
$ echo " 3918912k " | sed 's/ //g'
3918912k
Try this,
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
System.out.println("Yes option");
} else {
System.out.println("No Option");
}
Windows 7
Try this,
run cmd as Admin.
Unistall all iis.
start /w pkgmgr.exe /uu:IIS-WebServerRole;WAS-WindowsActivationService
Reinstall iis and normaly it's work
Alain
>>str = "http://www.domain.com/?s=some&two=20"
>>str.split("&")
>>["http://www.domain.com/?s=some", "two=20"]
So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :
var values = {name: 'misko', gender: 'male'};
Angular will take each value one by one the first one is name, the second is gender.
If your object to iterate on is an array (also possible), like this :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
Angular.forEach will take one by one starting by the first object, then the second object.
For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :
var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male
So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'
If this time you display an array, like this :
var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]
So then value is your object (collection), and key is the index of your array since :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
1: { "Name" : "Linda", "Password" : "lindatheQueen" }}
I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/
The problem seems to come from the fact $http.get()
is an asynchronous request.
You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach
without waiting the answer of your JSON.
You need to include the loop in the success function
var app = angular.module('testModule', [])
.controller('testController', ['$scope', '$http', function($scope, $http){
$http.get('Data/info.json').then(function(data){
$scope.data = data;
angular.forEach($scope.data, function(value, key){
if(value.Password == "thomasTheKing")
console.log("username is thomas");
});
});
});
This should work.
The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.
You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.
I'm not sure if I'm missing something here, but there's no reason why you can't add a listener to your panel.
In Netbeans, just hit the "Source" button in the top left of the editor window and you can edit most of the code. The actual layout code is mostly locked, but you can even customize that if you need to.
As far as I'm aware, txtMessage.requestFocusInWindow()
is supposed to set up the default focus for when the window is displayed the first time. If you want to request the focus after the window has been displayed already, you should use txtMessage.requestFocus()
For testing, you can just add a listener in the constructor:
addWindowListener(new WindowAdapter(){
public void windowOpened( WindowEvent e){
txtMessage.requestFocus();
}
});
Just add this code to .vimrc (or .gvimrc)
nnoremap <A-j> :m+<CR>==
nnoremap <A-k> :m-2<CR>==
inoremap <A-j> <Esc>:m+<CR>==gi
inoremap <A-k> <Esc>:m-2<CR>==gi
vnoremap <A-j> :m'>+<CR>gv=gv
vnoremap <A-k> :m-2<CR>gv=gv
A valid JavaScript identifier shuold must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables
Just had a requirement for this; here is the code I used. Apply it to an input as normal, I am using the class typeof__multidatepicker
.
It maintains a list of unique dates in the owner textbox. You can also type in there, this is not validated - obviously the server needs to check the resulting list!
I tried to get it to work with the datepicker's linked textbox but failed, so it creates an invisible input for the datepicker (it doesn't seem to work with display:none
, hence the odd styling).
It is positioned over the main input so the datepicker appears in the correct place, and is 1px in width so you can still type into the main textbox.
It's for an intranet with a fixed platform so I haven't done much cross-browser testing.
Remember to include the handler on the body
or it works confusingly.
$('.typeof__multidatepicker').each(
function()
{
var _this = $(this);
var picker = $('<input tabindex="-1" style="position:absolute;opacity:0;width:1px" type="text"/>');
picker.insertAfter(this)
.position({my:'left top', at:'left top', of:this})
.datepicker({
beforeShow:
function()
{
_this.data('mdp-popped', true);
},
onClose:
function(dt, dpicker)
{
var date = $.datepicker.formatDate(picker.datepicker('option', 'dateFormat'), picker.datepicker('getDate'));
var hash = {};
var curr = _this.val() ? _this.val().split(/\s*,\s*/) : [];
var a = [];
$.each(curr,
function()
{
if(this != '' && !/^\s+$/.test(this))
{
a.push(this);
hash[this] = true;
}
}
);
if(date && !hash[date])
{
a.push(date);
_this.val(a.join(', '));
}
_this.data('mdp-popped', false);
_this.data('mdp-justclosed', true);
}
});
_this.on('focus',
function(e)
{
if(!_this.data('mdp-popped') && !_this.data('mdp-justclosed'))
_this.next().datepicker('show');
_this.data('mdp-justclosed', false);
}
);
}
);
$('body').on('click', function(e) { $('.typeof__multidatepicker').data('mdp-justclosed', false); });
Tested this code using XCode 8 and Swift 3
To Add Custom View to SuperView use:
self.view.addSubview(myView)
To Remove Custom View from Superview use:
self.view.willRemoveSubview(myView)
You may have to first update all the records that are null to the default value then use the alter table statement.
Update dbo.TableName
Set
Created="01/01/2000"
where Created is NULL
Trim in array_map change type if you have NULL in value.
Better way to do it:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved
You could do:
import inspect
mydict = {'one': 1, 'two': 2}
source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print [x for x in source if x.startswith("mydict = ")]
Also: make sure not to shadow the dict builtin!
In Rails 4(Using HAML):
=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is return, you can avoid toast appear
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
The override
keyword serves two purposes:
To explain the latter:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... } // OK
}
class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};
In derived2
the compiler will issue an error for "changing the type". Without override
, at most the compiler would give a warning for "you are hiding virtual method by same name".
try this:
In [110]: (df.groupby('Company Name')
.....: .agg({'Organisation Name':'count', 'Amount': 'sum'})
.....: .reset_index()
.....: .rename(columns={'Organisation Name':'Organisation Count'})
.....: )
Out[110]:
Company Name Amount Organisation Count
0 Vifor Pharma UK Ltd 4207.93 5
or if you don't want to reset index:
df.groupby('Company Name')['Amount'].agg(['sum','count'])
or
df.groupby('Company Name').agg({'Amount': ['sum','count']})
Demo:
In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
Amount
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
Hi, This is my example of calculating the difference between two dates
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<br>
<input class='fromdate' type="date" />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />
<input class='todate' type="submit" onclick='showDays()' />
</body>
</html>
This is the function that calculates the difference :
function showDays(){
var start = $('.fromdate').val();
var end = $('.todate').val();
var startDay = new Date(start);
var endDay = new Date(end);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = endDay.getTime() - startDay.getTime();
var days = millisBetween / millisecondsPerDay;
// Round down.
alert( Math.floor(days));
}
I hope I have helped you
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
My fix to this very same issue was to add an option as a 3rd argument: charset
queryInterface.createTable(
tableName,
{ /*... columns*/ },
{ charset: 'utf8' }
)
Otherwise sequelize would create tables as utf8mb4.
Actually - Patrick's code sort of worked for me as well. The correct way to do it would be along the lines of this:
Note: there's a bit of jquery ahead:
if ($.browser.msie == false) {
var h = (document.getElementById("iframeID").contentDocument.body.offsetHeight);
} else {
var h = (document.getElementById("iframeID").Document.body.scrollHeight);
}
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
Per the documentation from GitHub regarding GFM syntax highlighted code blocks
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
Rendered on GitHub, console
makes the lines after the console blue. bash
, sh
, or shell
don't seem to "highlight" much ...and you can use posh
for PowerShell or CMD.
For Chrome Version 50+ for Mac Users. Close all opened chrome first and run the below command
open -a Google\ Chrome --args --disable-web-security --user-data-dir=""
The above will work. Thanks
I would definitely use html markers to achieve this. Just surround your text with <p></p>
or <font></font>
and add the desired attributes. See the following example:
<p style="font-family: times, serif; font-size:11pt; font-style:italic">
Why did we use these specific parameters during the calculation of the fingerprints?
</p>
This will produce the following output
compared to
This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.
Lastly, be aware that the html marker overrides the font styling used by Markdown.
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
Try Following
DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime
public class chkPalindrome{
public static String isPalindrome(String pal){
if(pal.length() == 1){
return pal;
}
else{
String tmp= "";
tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));
return tmp;
}
}
public static void main(String []args){
chkPalindrome hwObj = new chkPalindrome();
String palind = "MADAM";
String retVal= hwObj.isPalindrome(palind);
if(retVal.equals(palind))
System.out.println(palind+" is Palindrome");
else
System.out.println(palind+" is Not Palindrome");
}
}
In vi on Red Hat, I was able to insert carriage returns using just the \r character. I believe this internally executes 'ex' instead of 'sed', but it's similar, and vi can be another way to do bulk edits such as code patches. For example. I am surrounding a search term with an if statement that insists on carriage returns after the braces:
:.,$s/\(my_function(.*)\)/if(!skip_option){\r\t\1\r\t}/
Note that I also had it insert some tabs to make things align better.
Simple example below. Note you should pass in a larger buffer, and test to see if the buffer was large enough or not
void Log(LPCWSTR pFormat, ...)
{
va_list pArg;
va_start(pArg, pFormat);
char buf[1000];
int len = _vsntprintf(buf, 1000, pFormat, pArg);
va_end(pArg);
//do something with buf
}
In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2) {
//Do your code here
}
The errors in ASP.Net are saved on the Server.GetLastError property,
Or i would put a label on the asp.net page for displaying the error.
try
{
do something
}
catch (YourException ex)
{
errorLabel.Text = ex.Message;
errorLabel.Visible = true;
}
assylias and Head of Catering have already given your the reason why the error is occurring.
Now regarding what you are doing, from what I understand, you don't need to use Select
at all
I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as
Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String
filepath = CStr(FileDialog)
'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)
lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)
You can use this example to handle your problem:
System.out.printf( "%-15s %15s %n", "name", "lastname");
System.out.printf( "%-15s %15s %n", "Bill", "Smith");
You can play with the "%" until you find the right alignment to satisfy your needs
You sure can.
protected void GetColumNames_DataReader()
{
System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=localhost;database=northwind;trusted_connection=true");
System.Data.SqlClient.SqlCommand SqlCmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM Products", SqlCon);
SqlCon.Open();
System.Data.SqlClient.SqlDataReader SqlReader = SqlCmd.ExecuteReader();
System.Int32 _columncount = SqlReader.FieldCount;
System.Web.HttpContext.Current.Response.Write("SqlDataReader Columns");
System.Web.HttpContext.Current.Response.Write(" ");
for ( System.Int32 iCol = 0; iCol < _columncount; iCol ++ )
{
System.Web.HttpContext.Current.Response.Write("Column " + iCol.ToString() + ": ");
System.Web.HttpContext.Current.Response.Write(SqlReader.GetName( iCol ).ToString());
System.Web.HttpContext.Current.Response.Write(" ");
}
}
This is originally from: http://www.dotnetjunkies.ddj.com/Article/B82A22D1-8437-4C7A-B6AA-C6C9BE9DB8A6.dcik
you can simply do:
In[17]:df['combined']=df['bar'].astype(str)+'_'+df['foo']+'_'+df['new']
In[17]:df
Out[18]:
bar foo new combined
0 1 a apple 1_a_apple
1 2 b banana 2_b_banana
2 3 c pear 3_c_pear
Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.
request:
domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20
That should return a sorted pageable by field provided in the provided order.
First
pip install pymysql
Then put the code below into __init__.py
(projectname/__init__.py
)
import pymysql
pymysql.install_as_MySQLdb()
My environment is (python3.5, django1.10) and this solution works for me!
Hope this helps!!
quux00's answer only tells about comparing basic types.
If you need to compare types you defined, you shouldn't use reflect.TypeOf(xxx)
. Instead, use reflect.TypeOf(xxx).Kind()
.
There are two categories of types:
Here is a full example:
type MyFloat float64
type Vertex struct {
X, Y float64
}
type EmptyInterface interface {}
type Abser interface {
Abs() float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (f MyFloat) Abs() float64 {
return math.Abs(float64(f))
}
var ia, ib Abser
ia = Vertex{1, 2}
ib = MyFloat(1)
fmt.Println(reflect.TypeOf(ia))
fmt.Println(reflect.TypeOf(ia).Kind())
fmt.Println(reflect.TypeOf(ib))
fmt.Println(reflect.TypeOf(ib).Kind())
if reflect.TypeOf(ia) != reflect.TypeOf(ib) {
fmt.Println("Not equal typeOf")
}
if reflect.TypeOf(ia).Kind() != reflect.TypeOf(ib).Kind() {
fmt.Println("Not equal kind")
}
ib = Vertex{3, 4}
if reflect.TypeOf(ia) == reflect.TypeOf(ib) {
fmt.Println("Equal typeOf")
}
if reflect.TypeOf(ia).Kind() == reflect.TypeOf(ib).Kind() {
fmt.Println("Equal kind")
}
The output would be:
main.Vertex
struct
main.MyFloat
float64
Not equal typeOf
Not equal kind
Equal typeOf
Equal kind
As you can see, reflect.TypeOf(xxx)
returns the direct types which you might want to use, while reflect.TypeOf(xxx).Kind()
returns the basic types.
Here's the conclusion. If you need to compare with basic types, use reflect.TypeOf(xxx).Kind()
; and if you need to compare with self-defined types, use reflect.TypeOf(xxx)
.
if reflect.TypeOf(ia) == reflect.TypeOf(Vertex{}) {
fmt.Println("self-defined")
} else if reflect.TypeOf(ia).Kind() == reflect.Float64 {
fmt.Println("basic types")
}
LIke this
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: gray;
float: left;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
html
<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>
html
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details
</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
For the URI query use urlencode
/urldecode
; for anything else use rawurlencode
/rawurldecode
.
The difference between urlencode
and rawurlencode
is that
urlencode
encodes according to application/x-www-form-urlencoded (space is encoded with +
) whilerawurlencode
encodes according to the plain Percent-Encoding (space is encoded with %20
).I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.
If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...
Before going down the dll version path... Check closer to home and verify your thread code is not throwing.
This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA
used by the installer in its ADVAPI32.DLL
by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...
Because of that, the solution is actually quite easy:
get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip
), extract it too,
use unpack200
from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME
environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.
SET JAVA_HOME=C:\Program Files\Java\jdk8
Unpack all files with a single command (in batch file):
FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
Unpack all files with a single command (command line from JRE root):
FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
Unpack by manually locating the files and unpacking them one-by-one:
%JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
where packname
is for example rt
point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME%
and you're good to go.
Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\
to \lib\
(the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.
See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object
Try this
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
OP asked for users connected to a particular database:
-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity
WHERE datname = 'my_great_database';
This gets you all sorts of juicy info (as others have mentioned) such as
usesysid
)usename
)appname
), if it bothers to set that variable -- psql
does :-)client_addr
)query
)It's possible using multiple handlers.
import logging
import auxiliary_module
# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)
log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')
log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')
log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')
# remember to close the handlers
for handler in log.handlers:
handler.close()
log.removeFilter(handler)
Please see: https://docs.python.org/2/howto/logging-cookbook.html
You can use a sealed abstract class instead of the enumeration, for example:
sealed abstract class Constraint(val name: String, val verifier: Int => Boolean)
case object NotTooBig extends Constraint("NotTooBig", (_ < 1000))
case object NonZero extends Constraint("NonZero", (_ != 0))
case class NotEquals(x: Int) extends Constraint("NotEquals " + x, (_ != x))
object Main {
def eval(ctrs: Seq[Constraint])(x: Int): Boolean =
(true /: ctrs){ case (accum, ctr) => accum && ctr.verifier(x) }
def main(args: Array[String]) {
val ctrs = NotTooBig :: NotEquals(5) :: Nil
val evaluate = eval(ctrs) _
println(evaluate(3000))
println(evaluate(3))
println(evaluate(5))
}
}
here is a better answer found through Git docs.
This shows what the heroku remote is:
$ git remote get-url heroku
Found it here: https://git-scm.com/docs/git-remote Also in that document is a set-url, if you need to change it.
I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).
items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
you can also get the line if there are other characters before token
items=re.findall("^.*token.*$",s,re.MULTILINE)
The above works like grep token on unix and keyword 'in' or .contains in python and C#
s='''
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
'''
http://pythex.org/ matches the following 2 lines
....
....
token qwerty
I think you're looking for export
- though I could be wrong.. I've never played with tcsh before. Use the following syntax:
export VARIABLE=value
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
I think your port is probably open, but you don't have anything that listens on it.
The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.
To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)
This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.
These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.
Just add vertical-align:top for first td alone needed not for all td.
tr>td:first-child {_x000D_
vertical-align: top;_x000D_
}
_x000D_
<tr>_x000D_
<td>Description</td>_x000D_
<td>more text</td>_x000D_
</tr>
_x000D_
Don't skip John Papa's presentation from PDC Conference 2010. See it here.
Int
32 bits (4byte)
-2,147,483,648 to 2,147,483,647
Long
64 bits (8byte)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
If your usage of a variable falls in the 32 bit range, use Int
, else use long
. Usually long is used for scientific computations and stuff like that need much accuracy. (eg. value of pi).
An example of choosing one over the other is YouTube's case. They first defined video view counter as an
int
which was overflowed when more than 2,147,483,647 views where received to a popular video. Since anInt
counter cannot store any value more than than its range, YouTube changed the counter to a 64 bit variable and now can count up to 9,223,372,036,854,775,807 views. Understand your data and choose the type which fits as 64 bit variable will take double the memory than a 32 bit variable.
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
In Python file test.py
, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py
file must have correct privileges:
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
To make executable a file on unix-type platforms:
chmod +x myscript.py
I needed to unset $PGUSER
:
$ unset PGUSER
$ createuser -s postgres
You can do this natively with HTML5 <datalist>
:
<label>Choose a browser from this list:_x000D_
<input list="browsers" name="myBrowser" /></label>_x000D_
<datalist id="browsers">_x000D_
<option value="Chrome">_x000D_
<option value="Firefox">_x000D_
<option value="Internet Explorer">_x000D_
<option value="Opera">_x000D_
<option value="Safari">_x000D_
<option value="Microsoft Edge">_x000D_
</datalist>
_x000D_
The answers above pointed me in the right direction. Here is a generic version of what I got working:
var script = document.createElement('script');
script.src = 'http://' + location.hostname + '/module';
script.addEventListener('load', postLoadFunction);
document.head.appendChild(script);
function postLoadFunction() {
// add module dependent code here
}
As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.
The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.
s = requests.session()
s.config['keep_alive'] = False
Starting from AngularJS v1.4.8, you can use
get(url, config)
as follows:
var data = {
user_id:user.id
};
var config = {
params: data,
headers : {'Accept' : 'application/json'}
};
$http.get(user.details_path, config).then(function(response) {
// process response here..
}, function(response) {
});
Set type=submit
to the button you'd like to be default and type=button
to other buttons. Now in the form below you can hit Enter in any input fields, and the Render
button will work (despite the fact it is the second button in the form).
Example:
<button id='close_button' class='btn btn-success'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
type=submit> <!-- Here we use SUBMIT, not BUTTON -->
<span class='glyphicon glyphicon-send'> </span> Render
</button>
Tested in FF24 and Chrome 35.
You can use this query-
SELECT FORMAT (getdate(), 'dd/MMM/yy') as date
Hope, this query helps you.
Thanks!!
In your link.php your echo
statement must be like this:
echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';
Then in your pass.php you cannot use $a
because it was not initialized with your intended string value.
You can directly compare it to a string like this:
if($_GET['link'] == 'Link1')
Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a
and $b
variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.
Here is the solution I used for me Is works for fetching JSON from string
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}
Write this in each "new activity" after you initialized your new intent->
Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();
Since SysColumns is deprecated, use Sys.All_Columns
:
Select
ObjectName = Object_Name(Object_ID)
,T.Name
,C.*
,T.*
From
Sys.All_Columns C
Inner Join Sys.Types T On T.User_Type_Id = C.User_Type_Id
Where [Object_ID] = Object_ID('Sys.Server_Permissions')
--Order By Name Asc
Select * From Sys.Types
will yield user_type_id = ID
of the type. This is unique within the database. For system data types: user_type_id = system_type_id
.
Use this instead
echo $LINE | sed -e 's/12345678/$replace/g'
this works for me just simply remove the quotes
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
First Div
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
Second Div
</div>
</div>
This does the trick.
If you are trying to match the size as shown in Windows Explorer's detail view, this is the code you want:
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern long StrFormatKBSize(
long qdw,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszBuf,
int cchBuf);
public static string BytesToString(long byteCount)
{
var sb = new StringBuilder(32);
StrFormatKBSize(byteCount, sb, sb.Capacity);
return sb.ToString();
}
This will not only match Explorer exactly but will also provide the strings translated for you and match differences in Windows versions (for example in Win10, K = 1000 vs. previous versions K = 1024).
The more general answer to this question involves shadowed variables and how they are accessed.
In the following example (from Oracle), the variable x in main() is shadowing Test.x:
class Test {
static int x = 1;
public static void main(String[] args) {
InnerClass innerClassInstance = new InnerClass()
{
public void printX()
{
System.out.print("x=" + x);
System.out.println(", Test.this.x=" + Test.this.x);
}
}
innerClassInstance.printX();
}
public abstract static class InnerClass
{
int x = 0;
public InnerClass() { }
public abstract void printX();
}
}
Running this program will print:
x=0, Test.this.x=1
More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6
From version 9.1.4 you only need to import ReactiveFormsModule
first create database name "School" than create table "students" with following columns 1. id 2. name 3. address
now open visual studio and create connection:
namespace school { public partial class Form1 : Form { SqlConnection scon; public Form1() { InitializeComponent(); scon = new SqlConnection("Data Source = ABC-PC; trusted_connection = yes; Database = school; connection timeout = 30"); } //create command SqlCommand scom = new SqlCommand("insert into students (id,name,address) values(@id,@name,@address)", scon); //pass parameters scom.Parameters.Add("id", SqlDbType.Int); scom.Parameters["id"].Value = textBox1.Text; scom.Parameters.Add("name", SqlDbType.VarChar); scom.Parameters["name"].Value = this.textBox2.Text; scom.Parameters.Add("address", SqlDbType.VarChar); scom.Parameters["address"].Value = this.textBox6.Text; scon.Open(); scom.ExecuteNonQuery(); scon.Close(); reset(); }
also check solution here: http://solutions.musanitech.com/?p=6
You can pass a config object to axios like:
axios({
method: 'post',
url: '....',
params: {'HTTP_CONTENT_LANGUAGE': self.language},
headers: {'header1': value}
})
It looks like you are after the DateTime function add - use it like this:
$date = new DateTime();
date_add($date, new DateInterval("PT30M"));
(Note: untested, but according to the docs, it should work)
This is an old thread, but for reference it's important to note that disabling an input element's outline is not recommended as it hinders accessibility.
The outline property is there for a reason - providing users with a clear indication of keyboard focus. For further reading and additional sources about this subject see http://outlinenone.com/