Javascript has a dedicated operator for this: unary negation.
TL;DR: It's the minus sign!
To negate a number, simply prefix it with -
in the most intuitive possible way. No need to write a function, use Math.abs()
multiply by -1
or use the bitwise operator.
Unary negation works on number literals:
let a = 10; // a is `10`
let b = -10; // b is `-10`
It works with variables too:
let x = 50;
x = -x; // x is now `-50`
let y = -6;
y = -y; // y is now `6`
You can even use it multiple times if you use the grouping operator (a.k.a. parentheses:
l = 10; // l is `10`
m = -10; // m is `-10`
n = -(10); // n is `-10`
o = -(-(10)); // o is `10`
p = -(-10); // p is `10` (double negative makes a positive)
All of the above works with a variable as well.
You can also make it with BufferedReader if you want to validate user input, like this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Areas {
public static void main(String args[]){
float PI = 3.1416f;
int r=0;
String rad; //We're going to read all user's text into a String and we try to convert it later
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
System.out.println("Radius?");
try{
rad = br.readLine(); //We read from user's input
r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
}
catch(Exception e){
System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
Areas a = new Areas(); //We call this class again, so user can try it again
//You can also print exception in case you want to see it as follows:
// e.printStackTrace();
}
}
}
Because Scanner class won't allow you to do it, or not that easy...
And to validate you use "try-catch" calls.
You should never store values with format. Formatting should be done in the view depending on user preferences.
Searching for phone nunbers with mixed formatting is near impossible.
For this case I would split into fields and store as integer. Numbers are faster than texts and splitting them and putting index on them makes all kind of queries ran fast.
Leading 0 could be a problem but probably not. In Sweden all area codes start with 0 and that is removed if also a country code is dialed. But the 0 isn't really a part of the number, it's a indicator used to tell that I'm adding an area code. Same for country code, you add 00 to say that you use a county code.
Leading 0 shouldn't be stored, they should be added when needed. Say you store 00 in the database and you use a server that only works with + they you have to replace 00 with + for that application.
So, store numbers as numbers.
I had similar problem. I was trying to display results of Analog to Digital value from a Char type Array. The problem was when I was turning the Pot to get lower voltage or lower converted decimal value like 5 from between (1023 - 0), the lift over characters from array was staying beside the number 5. I used this method to get rid of the problem:
LCD_Send_String(" "); \ used spaces as string characters LCD_Send_Command (LCD_THIRD_ROW); \Returned the cursor back at the start of line.
Or you can use javascript to redirect to another page:
<script type="text/javascript">
function toRedirect() {
window.location.href="new.aspx";
}
</script>
Call this toRedirect()
function from client (for ex: onload event of body tag) or from server using:
ClientScript.RegisterStartupScript(this.gettype(),"Redirect","toRedirect()",true);
def getText():
file=open("ex1.txt","r");
names=file.read().split("\n");
for x,word in enumerate(names):
if(len(word)>=20):
return 0;
print "length of ",word,"is over 20"
break;
if(x==20):
return 0;
break;
else:
return names;
def show(names):
for word in names:
len_set=len(set(word))
print word," ",len_set
for i in range(1):
names=getText();
if(names!=0):
show(names);
else:
break;
I don't know about yum, but rpm -ql
will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.
Configuring $mail->SMTPAuth = true;
was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.
In Pandas, I like to use the shape
attribute to get number of rows.
df[df.A > 0].shape[0]
gives the number of rows matching the condition A > 0
, as desired.
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
I think you will have fewer problems if you declared a Property that implements INotifyPropertyChanged, then databind IsChecked
, SelectedIndex
(using IValueConverter) and Fill
(using IValueConverter) to it instead of using the Checked Event to toggle SelectedIndex
and Fill
.
There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.
In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".
>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]
How it works:
array.insert(index, value)
Insert an item at a given position. The first argument is the index of the element before which to insert, so array.insert(0, x)
inserts at the front of the list, and array.insert(len(array), x)
is equivalent to array.append(x)
.Negative values are treated as being relative to the end of the array.
There are a lot of good answers. The key is that you must set nestedScrollingEnabled
to false
. As mentioned above you can do it in java code:
mRecyclerView.setNestedScrollingEnabled(false);
But also you have an opportunity to set the same property in xml code (android:nestedScrollingEnabled="false"
):
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="match_parent" />
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
One thing that this doesn't answer is what happens when you click on one of the options in the select list after you have done your size = n and made it absolute positioning.
Because the blur event makes it size = 1 and changes it back to how it looks, you should have something like this as well
$("option").click(function(){
$(this).parent().blur();
});
Also, if you're having issues with the absolute positioned select list showing behind other elements, just put a
z-index: 100;
or something like that in the style of the select.
This one drove me crazy... basically you need two things:
1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.
2) You must add an additional website in IIS 7 named subdomain.example.com
The question is a bit unclear can't you just repeat the for loop?
a=[1,2,3]
for i in a:
print i
1
2
3
for i in a:
print i
1
2
3
Open extensions menu (Ctrl+Shift+X), and search .NuGet Package Manager.
Use FractionallySizedBox
widget.
FractionallySizedBox(
widthFactor: 1.0, // width w.r.t to parent
heightFactor: 1.0, // height w.r.t to parent
child: *Your Child Here*
}
This widget is also very useful when you want to size your child at a fractional of its parent's size.
Example:
If you want the child to occupy 50% width of its parent, provide
widthFactor
as0.5
Based on this test (for-vs-forEach-vs-reduce) and this (loops)
I can say that:
var total = 0;
for (var i = 0, n = array.length; i < n; ++i)
{
total += array[i];
}
For you case you won't need this, but it adds a lot of flexibility.
Array.prototype.Aggregate = function(fn) {
var current
, length = this.length;
if (length == 0) throw "Reduce of empty array with no initial value";
current = this[0];
for (var i = 1; i < length; ++i)
{
current = fn(current, this[i]);
}
return current;
};
Usage:
var total = array.Aggregate(function(a,b){ return a + b });
Then comes forEach
and reduce
which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.
I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.
Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force
Plus I needed to Filter and only copy *.config files.
This didn't work, with "\*" because it did not recurse
Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force
I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.
Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse |
ForEach-Object {
$childPath = "$_".substring($sourcePath.length+1)
$dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
Copy-Item -Verbose -Path $_ -Destination $dest -Force
}
There isn't, really. super()
looks at the next class in the MRO (method resolution order, accessed with cls.__mro__
) to call the methods. Just calling the base __init__
calls the base __init__
. As it happens, the MRO has exactly one item-- the base. So you're really doing the exact same thing, but in a nicer way with super()
(particularly if you get into multiple inheritance later).
If you want to use it with groups, you can use:
library(plyr)
mydata<-mtcars
ddply(mydata,.(carb),colwise(sd))
carb mpg cyl disp hp drat wt qsec vs am gear
1 1 6.001349 0.9759001 75.90037 19.78215 0.5548702 0.6214499 0.590867 0.0000000 0.5345225 0.5345225
2 2 5.472152 2.0655911 122.50499 43.96413 0.6782568 0.8269761 1.967069 0.5270463 0.5163978 0.7888106
3 3 1.053565 0.0000000 0.00000 0.00000 0.0000000 0.1835756 0.305505 0.0000000 0.0000000 0.0000000
4 4 3.911081 1.0327956 132.06337 62.94972 0.4575102 1.0536001 1.394937 0.4216370 0.4830459 0.6992059
5 6 NA NA NA NA NA NA NA NA NA NA
6 8 NA NA NA NA NA NA NA NA NA NA
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…
<body ng-app="">
<div ng-include="'myFile.htm'"></div>
</body>
Use .getAbsolutePath() on your File object.
getClass().getResource("somefile").getFile().getAbsolutePath()
You may like lfqueue, https://github.com/Taymindis/lfqueue. It’s lock free concurrent queue. I’m currently using it to consuming the queue from multiple incoming calls and works like a charm.
The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):
C# Collection was modified; enumeration operation may not execute.
Your problem is the loop
foreach (KeyValuePair<int, int> kvp in rankings) {
//
}
wherein you modify the collection rankings
. In particular, the offensive line is
rankings[kvp.Key] = rankings[kvp.Key] + 4;
Before you enter the loop, add the following line:
var listOfRankingsToModify = new List<int>();
Replace the offending line with
listOfRankingsToModify.Add(kvp.Key);
and after you exit the loop
foreach(var key in listOfRankingsToModify) {
rankings[key] = rankings[key] + 4;
}
That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.
Nick Craver's solution works but you can also use this:
:nth-last-child(n+2) { /* Your code here */ }
Chris Coyier of CSS Tricks made a nice :nth tester for this.
UPDATE: Turned my solution into a stand-alone python script.
This solution has saved me more than once. Hopefully others find it useful. This python script will find any jupyter kernel using more than cpu_threshold
CPU and prompts the user to send a SIGINT
to the kernel (KeyboardInterrupt). It will keep sending SIGINT
until the kernel's cpu usage goes below cpu_threshold
. If there are multiple misbehaving kernels it will prompt the user to interrupt each of them (ordered by highest CPU usage to lowest). A big thanks goes to gcbeltramini for writing code to find the name of a jupyter kernel using the jupyter api. This script was tested on MACOS with python3 and requires jupyter notebook, requests, json and psutil.
Put the script in your home directory and then usage looks like:
python ~/interrupt_bad_kernels.py
Interrupt kernel chews cpu.ipynb; PID: 57588; CPU: 2.3%? (y/n) y
Script code below:
from os import getpid, kill
from time import sleep
import re
import signal
from notebook.notebookapp import list_running_servers
from requests import get
from requests.compat import urljoin
import ipykernel
import json
import psutil
def get_active_kernels(cpu_threshold):
"""Get a list of active jupyter kernels."""
active_kernels = []
pids = psutil.pids()
my_pid = getpid()
for pid in pids:
if pid == my_pid:
continue
try:
p = psutil.Process(pid)
cmd = p.cmdline()
for arg in cmd:
if arg.count('ipykernel'):
cpu = p.cpu_percent(interval=0.1)
if cpu > cpu_threshold:
active_kernels.append((cpu, pid, cmd))
except psutil.AccessDenied:
continue
return active_kernels
def interrupt_bad_notebooks(cpu_threshold=0.2):
"""Interrupt active jupyter kernels. Prompts the user for each kernel."""
active_kernels = sorted(get_active_kernels(cpu_threshold), reverse=True)
servers = list_running_servers()
for ss in servers:
response = get(urljoin(ss['url'].replace('localhost', '127.0.0.1'), 'api/sessions'),
params={'token': ss.get('token', '')})
for nn in json.loads(response.text):
for kernel in active_kernels:
for arg in kernel[-1]:
if arg.count(nn['kernel']['id']):
pid = kernel[1]
cpu = kernel[0]
interrupt = input(
'Interrupt kernel {}; PID: {}; CPU: {}%? (y/n) '.format(nn['notebook']['path'], pid, cpu))
if interrupt.lower() == 'y':
p = psutil.Process(pid)
while p.cpu_percent(interval=0.1) > cpu_threshold:
kill(pid, signal.SIGINT)
sleep(0.5)
if __name__ == '__main__':
interrupt_bad_notebooks()
In my case the solution was (on top of adjustments suggested above) to restart my/users' local development computer / IIS (hosting server). My user has just been added to the newly created AD security group - and policy didn't apply to user AD account until I logged out/restarted my computer.
Hope this will help someone.
In PHP.js, $_COOKIE is a function ;-)
function $_COOKIE(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length).replace(/\+/g, '%20'));
}
return null;
}
Unfortunately, the built in php function get_meta_tags() requires the name parameter, and certain sites, such as twitter leave that off in favor of the property attribute. This function, using a mix of regex and dom document, will return a keyed array of metatags from a webpage. It checks for the name parameter, then the property parameter. This has been tested on instragram, pinterest and twitter.
/**
* Extract metatags from a webpage
*/
function extract_tags_from_url($url) {
$tags = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$contents = curl_exec($ch);
curl_close($ch);
if (empty($contents)) {
return $tags;
}
if (preg_match_all('/<meta([^>]+)content="([^>]+)>/', $contents, $matches)) {
$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="utf-8" ?>' . implode($matches[0]));
$tags = array();
foreach($doc->getElementsByTagName('meta') as $metaTag) {
if($metaTag->getAttribute('name') != "") {
$tags[$metaTag->getAttribute('name')] = $metaTag->getAttribute('content');
}
elseif ($metaTag->getAttribute('property') != "") {
$tags[$metaTag->getAttribute('property')] = $metaTag->getAttribute('content');
}
}
}
return $tags;
}
Go to your Microsoft SDKs directory. A path like this:
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools
Open the WCF Configuration Editor (Microsoft Service Configuration Editor) from that directory:
SvcConfigEditor.exe
(another option to open this tool is by navigating in Visual Studio 2017 to "Tools" > "WCF Service Configuration Editor")
Open your .config file or create a new one using the editor and navigate to Diagnostics.
There you can click the "Enable MessageLogging".
More info: https://msdn.microsoft.com/en-us/library/ms732009(v=vs.110).aspx
With the trace viewer from the same directory you can open the trace log files:
SvcTraceViewer.exe
You can also enable tracing using WMI. More info: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx
Just do:
0 */2 * * * /home/username/test.sh
The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)
Don't forget, you can check syslog to see if it ever actually ran!
why don't you use width: 100%
and height: 100%
.
Removing the focus after the cell value changes allow the values to update in the DataGridView. Remove the focus by setting the CurrentCell to null.
private void DataGridView1OnCellValueChanged(object sender, DataGridViewCellEventArgs dataGridViewCellEventArgs)
{
// Remove focus
dataGridView1.CurrentCell = null;
// Put in updates
Update();
}
private void DataGridView1OnCurrentCellDirtyStateChanged(object sender, EventArgs eventArgs)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:
[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
public string Name;
}
public class Derived : Base
{
public string Something;
}
Now when you serialize object in json will be add "$type"
with "base"
and "derived"
value and it will be use for deserialize
Serialized list example:
[
{"Name":"some name", "$type":"base"},
{"Name":"some name", "Something":"something", "$type":"derived"}
]
If you want to just accept defaults you can use:
\n | ./shell_being_run
I encountered this exception message as well. For me the problem was different. I wanted to delete a parent.
In one transaction:
It turns out that I had to do two separate transactions. I committed after referencing the field in the child. Then started a new commit for the delete.
There was no need to delete the child elements or empty the collections in the parent (assuming orphanRemoval = true
.). In fact, this didn't work.
In sum, this error appears if you have a reference to a field in a child object when that object is being deleted.
I'm assuming you mean a datetime picker in a winforms application.
in your code, you can do the following:
string theDate = dateTimePicker1.Value.ToShortDateString();
or, if you'd like to specify the format of the date:
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
I would use ternary operators to categorize your switch conditions.
So...
switch( number > 9 ? "High" :
number > 5 ? "Mid" :
number > 1 ? "Low" : "Floor")
{
case "High":
do the thing;
break;
case "Mid":
do the other thing;
break;
case "Low":
do something else;
break;
case "Floor":
do whatever;
break;
}
To do this:
open terminal
type in the terminal: nano
; which is a text editor available for the terminal. when you do this. something like this would appear.
here you can type in your C
program
type in control(^) + x
-> which means to exit.
save the file by typing in y
to save the file
write the file name; e.g. helloStack.c
(don't forget to add .c)
when this appears, type in gcc helloStack.c
./a.out
: this should give you your result!!private class ObjectAdapter extends BaseAdapter {
private Context context;
private List<Object>objects;
public ObjectAdapter(Context context, List<Object> objects) {
this.context = context;
this.objects = objects;
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
holder.text = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(getItem(position).toString()));
return convertView;
}
class ViewHolder {
TextView text;
}
}
This is late, but here is my python implementation of the flowingdata NBA heatmap.
updated:1/4/2014: thanks everyone
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# ------------------------------------------------------------------------
# Filename : heatmap.py
# Date : 2013-04-19
# Updated : 2014-01-04
# Author : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
# http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------
import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline
page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)
# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)
nba_sort['PTS'].head(10)
# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)
# turn off the frame
ax.set_frame_on(False)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
# Set the labels
# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)
# rotate the
plt.xticks(rotation=90)
ax.grid(False)
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
The output looks like this:
There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.
If you use a type="button"
with an onclick
handler to login using ajax
, then the browser won't offer to save the password.
<form id="loginform">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="doLogin" type="button" value="Login" onclick="login(this.form);" />
</form>
Since this form does not have a submit button and has no action field, the browser will not offer to save the password.
However, if you change the button to type="submit"
and handle the submit, then the browser will offer to save the password.
<form id="loginform" action="login.php" onSubmit="return login(this);">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="doLogin" type="submit" value="Login" />
</form>
Using this method, the browser should offer to save the password.
Here's the Javascript used in both methods:
function login(f){
var username = f.username.value;
var password = f.password.value;
/* Make your validation and ajax magic here. */
return false; //or the form will post your data to login.php
}
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
UPDATE: Since this answer was written, Visibility
was introduced and provides the best solution to this problem.
You can use Opacity
with an opacity:
of 0.0
to draw make an element hidden but still occupy space.
To make it not occupy space, replace it with an empty Container()
.
EDIT: To wrap it in an Opacity object, do the following:
new Opacity(opacity: 0.0, child: new Padding(
padding: const EdgeInsets.only(
left: 16.0,
),
child: new Icon(pencil, color: CupertinoColors.activeBlue),
))
Google Developers quick tutorial on Opacity: https://youtu.be/9hltevOHQBw
I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!
import java.awt.datatransfer.*;
import java.awt.Toolkit;
private void /* Action performed when the copy to clipboard button is clicked */ {
String ctc = txtCommand.getText().toString();
StringSelection stringSelection = new StringSelection(ctc);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
// txtCommand is the variable of a text box
One-to-many and Many-to-one relationship is talking about the same logical relationship, eg an Owner may have many Homes, but a Home can only have one Owner.
So in this example Owner is the One, and Homes are the Many. Each Home always has an owner_id (eg the Foreign Key) as an extra column.
The difference in implementation between these two, is which table defines the relationship. In One-to-Many, the Owner is where the relationship is defined. Eg, owner1.homes lists all the homes with owner1's owner_id In Many-to-One, the Home is where the relationship is defined. Eg, home1.owner lists owner1's owner_id.
I dont actually know in what instance you would implement the many-to-one arrangement, because it seems a bit redundant as you already know the owner_id. Perhaps its related to cleanness of deletions and changes.
If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same value
and ng-model
, is checked automatically.
<input type="radio" value="1" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="2" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="3" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="4" ng-model="myRating" name="rating" class="radio">
If the value of myRating
is "2" then second radio button is selected.
the jnr-process project provides this capability.
It is part of the java native runtime used by jruby and can be considered a prototype for a future java-FFI
Create method in UserManager<TUser, TKey>
public Task<IdentityResult> ChangePassword(int userId, string newPassword)
{
var user = Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
return new Task<IdentityResult>(() => IdentityResult.Failed());
var store = Store as IUserPasswordStore<User, int>;
return base.UpdatePassword(store, user, newPassword);
}
Just set the time and date to variables if it will be something that will be in a loop then
:top
set T=%time%
set D=%Date%
echo %T%>>log.txt
echo %d%>>log.txt
echo time:%T%
echo date:%D%
pause
goto top
I suggest making it nice and clean by putting:
@echo off
in front of every thing it get rid of the rubbish C:/users/example/...
and putting
cls
after the :top
to clear the screen before it add the new date and time to the display
This way you don't need to add the CSS outside of the component:
@Component({
selector: 'body',
template: 'app-element',
// prefer decorators (see below)
// host: {'[class.someClass]':'someField'}
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
// alternatively also the host parameter in the @Component()` decorator can be used
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<body>`
//this.cdRef.detectChanges();
}
}
This CSS is defined inside the component and the selector is only applied if the class someClass
is set on the host element (from outside):
:host(.someClass) {
background-color: red;
}
If, in addition to automatic two-way binding, you want to call a function when a value changes, you can break the two-way binding shortcut syntax to the more verbose version.
<input [(ngModel)]="yourVar"></input>
is shorthand for
<input [ngModel]="yourVar" (ngModelChange)="yourVar=$event"></input>
(see e.g. http://victorsavkin.com/post/119943127151/angular-2-template-syntax)
You could do something like this:
<input [(ngModel)]="yourVar" (ngModelChange)="changedExtraHandler($event)"></input>
This might help? :)
Just search for the character at index 0 and compare it against the value you're looking for!
Reply to abccd and Question to anyone:
The command: C:\Python34\Scripts>py -3 -m pip install pandas
executed just fine. Unfortunately, I can't import Pandas.
Directory path: C:\users\myname\downloads\miniconda3\lib\site-packages
My Question: How is it that Pandas' dependency packages(numpy, python-dateutil, pytz, six) also having the same above directory path are able to import just fine but Pandas does not?
import pandas
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
import pandas
ImportError: No module named 'pandas'
I finally got Pandas reinstalled and imported with the help of the following web pages: *http://pandas.pydata.org/pandas-docs/stable/pandas.pdf (Pages 403 and 404 of 2215 ... 2.2.2 Installing Pandas with Miniconda) *https://conda.io/docs/user-guide/install/download.html *https://conda.io/docs/user-guide/getting-started.html
After installing Miniconda, I created a new environment area to get Pandas reinstalled and imported. This new environment included the current Python version 3.6.3. I could not import Pandas using Python 3.4.4.
I have encountered the same problem while my first Spring boot application.
In tutorial i could see following dependency to start sample application
I have done the same, my Spring STS is recognizing all class but when i am annotating my main class with @SpringBootApplication it's not recognizing this class whereas i could see jar was available in the class path.
I have following to resolve issues
After that it worked.
Thanks
As a follow-up to Adam Matan's answer, the /proc/<pid>
directory's time stamp as such is not necessarily directly useful, but you can use
awk -v RS=')' 'END{print $20}' /proc/12345/stat
to get the start time in clock ticks since system boot.1
This is a slightly tricky unit to use; see also convert jiffies to seconds for details.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat
This should give you seconds, which you can pass to strftime()
to get a (human-readable, or otherwise) timestamp.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat
Updated with some fixes from Stephane Chazelas in the comments; thanks as always!
If you only have Mawk, maybe try
awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
NR==1 { now=$1; next }
END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}
1 man proc; search for starttime.
For normal inlined <code>
use:
<code>...</code>
and for each and every place where blocked <code>
is needed use
<code style="display:block; white-space:pre-wrap">...</code>
Alternatively, define a <codenza>
tag for break lining block <code>
(no classes)
<script>
</script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>`
Testing:
(NB: the following is a scURIple utilizing a data:
URI protocol/scheme, therefore the %0A
nl format codes are essential in preserving such when cut and pasted into the URL bar for testing - so view-source:
(ctrl-U) looks good preceed every line below with %0A
)
data:text/html;charset=utf-8,<html >
<script>document.write(window.navigator.userAgent)</script>
<script></script>
<style>
codenza, code {} /* noop mnemonic aide that codenza mimes code tag */
codenza {display:block;white-space:pre-wrap}
</style>
<p>First using the usual <code> tag
<code>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
and then
<p>with the tag blocked using pre-wrapped lines
<code style=display:block;white-space:pre-wrap>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</code>
<br>using an ersatz tag
<codenza>
%0A function x(arghhh){
%0A return "a very long line of text that will extend the code beyond the boundaries of the margins, guaranteed for the most part, well maybe without you as a warrantee (except in abnormally conditioned perverse environs in which case a warranty is useless)"
%0A }
</codenza>
</html>
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:
.style1[disabled] { ... }
Worked ok on IE8.
Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:
var offset = $('#whatever').offset();
offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));
You should be able to do this like (as you're using the query api):
Entrant.where("pincode").ne(null)
... which will result in a mongo query resembling:
entrants.find({ pincode: { $ne: null } })
A few links that might help:
Since PowerShell doesn't support "-Credential" usage via many of the cmdlets (very annoying), and mapping a network drive via WMI proved to be very unreliable in PS, I found pre-caching the user credentials via a net use command to work quite well:
# cache credentials for our network path
net use \\server\C$ $password /USER:$username
Any operation that uses \\server\C$ in the path seems to work using the *-item cmdlets.
You can also delete the share when you're done:
net use \\server\C$ /delete
If you have to choose between __repr__
or __str__
go for the first one, as by default implementation __str__
calls __repr__
when it wasn't defined.
Custom Vector3 example:
class Vector3(object):
def __init__(self, args):
self.x = args[0]
self.y = args[1]
self.z = args[2]
def __repr__(self):
return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)
def __str__(self):
return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)
In this example, repr
returns again a string that can be directly consumed/executed, whereas str
is more useful as a debug output.
v = Vector3([1,2,3])
print repr(v) #Vector3([1,2,3])
print str(v) #x:1, y:2, z:3
Host in local IP,
Open CMD : ipconfig
Wireless LAN adapter Wi-Fi: IPv4 Address. . . . . . . . . . . : xx.xxx.xx.xxx
now 2 versions of metricsreloaded available. One supported on v9 and v10 isavailable here http://plugins.intellij.net/plugin/?idea&id=93
browser.execute_script('''window.open("http://bings.com","_blank");''')
Where browser is the webDriver
In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.
The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:background="#33AAFF"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
Activity / Fragment / Custom view
//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin = 200;
root.addView(img, params);
//...
This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:
You can do a function like this:
def getLastItem(dictionary):
last_keyval = dictionary.popitem()
dictionary.update({last_keyval[0]:last_keyval[1]})
return {last_keyval[0]:last_keyval[1]}
This not change the original dictionary! This happen because the popitem() function returns a tuple and we can utilize this for us favor!!
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
If you reference the sheet from another sheet, you can get the sheet name using the CELL function. You can then use regex to extract out the sheet name.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
update: The formula will automatically update 'SHEET NAME' with future changes, but you will need to reference a cell (such as A1) on that sheet when the formula is originally entered.
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
Maybe you want to use CSS "clip-path" (Works with transparency and background)
"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
Generator: http://bennettfeely.com/clippy/
Example:
/* With percent */_x000D_
.element-percent {_x000D_
background: red;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
background: blue;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
You can also use:
CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02.0f", currentDate.hour, currentDate.minute, currentDate.second];
CFRelease(currentDate); // Don't forget this! VERY important
I think this has the following advantages:
I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:
protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(catalog)
.withFunctionName(functionName)
.withReturnValue()
.declareParameters(buildSqlParameters());
return call;
}
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
};
}
The buildSqlParameters method should have included the SqlOutParameter:
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
new SqlOutParameter("l_clob", Types.CLOB) // <-- This was missing!
};
}
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
Try To Give Full path for reading image.
Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));
your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java
If the object of your class is created at end your code works fine for me and displays the image
// PracticeFrame pframe = new PracticeFrame();//comment this
new PracticeFrame().add(panel);
You can't do it without a full CSV parser.
for (var i in conf) {
val = conf[i];
console.log(val.path);
}
Update:
Now you should use new availability checking introduced with Swift 2:
e.g. To check for iOS 9.0 or later at compile time use this:
if #available(iOS 9.0, *) {
// use UIStackView
} else {
// show sad face emoji
}
or can be used with whole method or class
@available(iOS 9.0, *)
func useStackView() {
// use UIStackView
}
For more info see this.
Run time checks:
if you don't want exact version but want to check iOS 9,10 or 11 using if:
let floatVersion = (UIDevice.current.systemVersion as NSString).floatValue
EDIT: Just found another way to achieve this:
let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1)
let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1)
Just another perspective using DataTable
. Declare a DataTable
with 2 columns called index
and val
. Add an AutoIncrement
option and both AutoIncrementSeed
and AutoIncrementStep
values 1
to the index
column. Then use a foreach
loop and insert each array item into the datatable
as a row. Then by using Select
method, select the row having the maximum value.
Code
int[] anArray = { 1, 5, 2, 7 };
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("index"), new DataColumn("val")});
dt.Columns["index"].AutoIncrement = true;
dt.Columns["index"].AutoIncrementSeed = 1;
dt.Columns["index"].AutoIncrementStep = 1;
foreach(int i in anArray)
dt.Rows.Add(null, i);
DataRow[] dr = dt.Select("[val] = MAX([val])");
Console.WriteLine("Max Value = {0}, Index = {1}", dr[0][1], dr[0][0]);
Output
Max Value = 7, Index = 4
Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.
1st start Powershell "as Administrator" that will also prevent the error you got from docker version
.
The try to start the docker service: start-service docker
If that fails delete the docker.pid file you will find with cd $env:programfiles\docker; rm docker.pid
Finally you should change HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\VSmbDisableOplocks
to 0
or delete the value.
I wrote a Tester
class which can test the performance:
public class Tester
{
public static void main(String[] args)
{
String text = "";
int loopCount = 10000000;
long startTime, endTime, duration1, duration2;
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.equals("");
}
endTime = System.nanoTime();
duration1 = endTime - startTime;
System.out.println(".equals(\"\") duration " +": \t" + duration1);
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.isEmpty();
}
endTime = System.nanoTime();
duration2 = endTime - startTime;
System.out.println(".isEmpty() duration "+": \t\t" + duration2);
System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
}
}
I found that using .isEmpty()
took around half the time of .equals("")
.
row from a database table
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
As others answers are correct, but too simple, so for completeness I'm presenting below code snippet to perform SELECT COUNT
on a sophisticated JPA Criteria query (with multiple joins, fetches, conditions).
It is slightly modified this answer.
public <T> long count(final CriteriaBuilder cb, final CriteriaQuery<T> selectQuery,
Root<T> root) {
CriteriaQuery<Long> query = createCountQuery(cb, selectQuery, root);
return this.entityManager.createQuery(query).getSingleResult();
}
private <T> CriteriaQuery<Long> createCountQuery(final CriteriaBuilder cb,
final CriteriaQuery<T> criteria, final Root<T> root) {
final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
final Root<T> countRoot = countQuery.from(criteria.getResultType());
doJoins(root.getJoins(), countRoot);
doJoinsOnFetches(root.getFetches(), countRoot);
countQuery.select(cb.count(countRoot));
countQuery.where(criteria.getRestriction());
countRoot.alias(root.getAlias());
return countQuery.distinct(criteria.isDistinct());
}
@SuppressWarnings("unchecked")
private void doJoinsOnFetches(Set<? extends Fetch<?, ?>> joins, Root<?> root) {
doJoins((Set<? extends Join<?, ?>>) joins, root);
}
private void doJoins(Set<? extends Join<?, ?>> joins, Root<?> root) {
for (Join<?, ?> join : joins) {
Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
joined.alias(join.getAlias());
doJoins(join.getJoins(), joined);
}
}
private void doJoins(Set<? extends Join<?, ?>> joins, Join<?, ?> root) {
for (Join<?, ?> join : joins) {
Join<?, ?> joined = root.join(join.getAttribute().getName(), join.getJoinType());
joined.alias(join.getAlias());
doJoins(join.getJoins(), joined);
}
}
Hope it saves somebody's time.
Because IMHO JPA Criteria API is not intuitive nor quite readable.
Typical, found it right after posting this question in despair; the tool I was looking for was:
$ aapt dump badging <my_apk.apk>
Here's another approach (assuming you have control of the HTML): add an empty <span></span>
right after the input, and target that in CSS using input.mystyle + span:after
.field_with_errors {_x000D_
display: inline;_x000D_
color: red;_x000D_
}_x000D_
.field_with_errors input+span:after {_x000D_
content: "*"_x000D_
}
_x000D_
<div class="field_with_errors">Label:</div>_x000D_
<div class="field_with_errors">_x000D_
<input type="text" /><span></span> _x000D_
</div>
_x000D_
I'm using this approach in AngularJS because it will add .ng-invalid
classes automatically to <input>
form elements, and to the form, but not to the <label>
.
Since you've already received help on the query, I'll take a poke at your syntax question:
The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join
and on
clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.
Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:
select
count(*)
from Table1 as t1
join Table2 as t2
join Table3 as t3
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:
select
count(*)
from Table1 as t1
join Table3 as t3
join Table2 as t2
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.
A slightly less verbose way of declaring named enumerations:
object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
type WeekDay = Value
val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}
WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString // returns Fri
Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
Simple str_replace
with count parameter would work here:
$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
echo "One of Array value is present in the string.";
}
More Info - https://www.techpurohit.com/extended-behaviour-explode-and-strreplace-php
For current date just use UNIX_TIMESTAMP()
in your MySQL query.
If you want to replace an empty string and records with only spaces, the correct answer is!:
df = df.replace(r'^\s*$', np.nan, regex=True)
The accepted answer
df.replace(r'\s+', np.nan, regex=True)
Does not replace an empty string!, you can try yourself with the given example slightly updated:
df = pd.DataFrame([
[-0.532681, 'foo', 0],
[1.490752, 'bar', 1],
[-1.387326, 'fo o', 2],
[0.814772, 'baz', ' '],
[-0.222552, ' ', 4],
[-1.176781, 'qux', ''],
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))
Note, also that 'fo o' is not replaced with Nan, though it contains a space. Further note, that a simple:
df.replace(r'', np.NaN)
Does not work either - try it out.
You can also do it "the joiner way" by inserting "U+2060
Word Joiner".
If Accept-Charset
permits, the unicode character itself can be inserted directly into the HTML output.
Otherwise, it can be done using entity encoding. E.g. to join the text red-brown
, use:
red-⁠brown
or (decimal equivalent):
red-⁠brown
. Another usable character is "U+FEFF
Zero Width No-break Space"[ 1 ]:
red-brown
and (decimal equivalent):
red-brown
[1]: Note that while this method still works in major browsers like Chrome, it has been deprecated since Unicode 3.2.
Comparison of "the joiner way" with "U+2011
Non-breaking Hyphen":
The word joiner can be used for all other characters, not just hyphens.
When using the word joiner, most renderers will rasterize the text identically. On Chrome, FireFox, IE, and Opera, the rendering of normal hyphens, eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
is identical to the rendering of normal hyphens (with U+2060 Word Joiner), eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
while the above two renders differ from the rendering of "Non-breaking Hyphen", eg:
a‑b‑c‑d‑e‑f‑g‑h‑i‑j‑k‑l‑m‑n‑o‑p‑q‑r‑s‑t‑u‑v‑w‑x‑y‑z
. (The extent of the difference is browser-dependent and font-dependent. E.g. when using a font declaration of "arial
", Firefox and IE11 show relatively huge variations, while Chrome and Opera show smaller variations.)
Comparison of "the joiner way" with <span class=c1></span>
(CSS .c1 {white-space:nowrap;}
) and <nobr></nobr>
:
The word joiner can be used for situations where usage of HTML tags is restricted, e.g. forms of websites and forums.
On the spectrum of presentation and content, majority will consider the word joiner to be closer to content, when compared to tags.
• As tested on Windows 8.1 Core 64-bit using:
• IE 11.0.9600.18205
• Firefox 43.0.4
• Chrome 48.0.2564.109 (Official Build) m (32-bit)
• Opera 35.0.2066.92
To get the maximum value of a column across a set of rows:
SELECT MAX(column1) FROM table; -- expect one result
To get the maximum value of a set of columns, literals, or variables for each row:
SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results
This one I implemented for my website , If some one got more no's of menu item and longer search bar can use this
Here is the code
<style>
.navbar-inverse .navbar-nav > li > a {
color: white !important;
}
.navbar-inverse .navbar-nav > li > a:hover {
text-decoration: underline;
}
.navbar-collapse ul li {
padding-top: 0px;
padding-bottom: 0px;
}
.navbar-collapse ul li a {
padding-top: 0px;
padding-bottom: 0px;
}
.navbar-brand img {
width: 200px;
height: 40px;
}
.navbar-inverse {
background-color: #3A1B37;
}
</style>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" runat="server" href="~/">
<img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin"></a>
<div class="col-md-6 col-sm-8 col-xs-11 navbar-left">
<div class="navbar-form " role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term" style="max-width: 100%; width: 100%;">
<div class="input-group-btn">
<button class="btn btn-default" style="background: rgb(72, 166, 72);" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="navbar-brand visible-md visible-lg visible-sm" style="visibility: hidden;" runat="server">
<img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin" />
</li>
<li><a runat="server" href="~/">Home</a></li>
<li><a runat="server" href="~/About">About</a></li>
<li><a runat="server" href="~/Contact">Contact</a></li>
<li><a runat="server" href="~/">Somthing</a></li>
<li><a runat="server" href="~/">Somthing</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Register">Register</a></li>
<li><a runat="server" href="~/Account/Login">Log in</a></li>
</ul> </div>
</div>
</div>
As others have pointed out, the only way to change the browser's behavior is to make sure the response either does not contain a 401 status code or if it does, not include the WWW-Authenticate: Basic
header. Since changing the status code is not very semantic and undesirable, a good approach is to remove the WWW-Authenticate
header. If you can't or don't want to modify your web server application, you can always serve or proxy it through Apache (if you are not using Apache already).
Here is a configuration for Apache to rewrite the response to remove the WWW-Authenticate header IFF the request contains contains the header X-Requested-With: XMLHttpRequest
(which is set by default by major Javascript frameworks such as JQuery/AngularJS, etc...) AND the response contains the header WWW-Authenticate: Basic
.
Tested on Apache 2.4 (not sure if it works with 2.2).
This relies on the mod_headers
module being installed.
(On Debian/Ubuntu, sudo a2enmod headers
and restart Apache)
<Location />
# Make sure that if it is an XHR request,
# we don't send back basic authentication header.
# This is to prevent the browser from displaying a basic auth login dialog.
Header unset WWW-Authenticate "expr=req('X-Requested-With') == 'XMLHttpRequest' && resp('WWW-Authenticate') =~ /^Basic/"
</Location>
Here's how to do it:
var myVideo = document.getElementById("my-video")
myVideo.controls = false;
Working example: https://jsfiddle.net/otnfccgu/2/
See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp
If your intention or the context of this question is really garbage collection, then you can set the datasets and datatables to null explicitly or use the keyword using and let them go out of scope. Dispose does not do much as Tetraneutron said it earlier. GC will collect dataset objects that are no longer referenced and also those that are out of scope.
I really wish SO forced people down voting to actually write a comment before downvoting the answer.
DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;
ls -lh file.txt | awk '{ print $5 }'
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
In plain Javascript, you could use Array#reduce
with an object
var cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }],_x000D_
result = cars.reduce(function (r, a) {_x000D_
r[a.make] = r[a.make] || [];_x000D_
r[a.make].push(a);_x000D_
return r;_x000D_
}, Object.create(null));_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
Here is a pretty simple function of AlertView in Swift :
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
You have to pass message as a String where you use this function.
As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.
The need is the possible desire for reproducible results, which may for example come from trying to debug your program, or of course from trying to redo what it does:
These two results we will "never" reproduce as I just asked for something "random":
R> sample(LETTERS, 5)
[1] "K" "N" "R" "Z" "G"
R> sample(LETTERS, 5)
[1] "L" "P" "J" "E" "D"
These two, however, are identical because I set the seed:
R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R> set.seed(42); sample(LETTERS, 5)
[1] "X" "Z" "G" "T" "O"
R>
There is vast literature on all that; Wikipedia is a good start. In essence, these RNGs are called Pseudo Random Number Generators because they are in fact fully algorithmic: given the same seed, you get the same sequence. And that is a feature and not a bug.
You forgot to seek:
str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
here is one with css + jquery (javascript) solution.
here is demo link Demo
//html
<div id="uberbar">
<a href="#top">Top of Page</a>
<a href="#bottom">Bottom of Page</a>
</div>
//css
#uberbar {
border-bottom:1px solid #eb7429;
background:#fc9453;
padding:10px 20px;
position:fixed;
top:0;
left:0;
z-index:2000;
width:100%;
}
//jquery
$(document).ready(function() {
(function() {
//settings
var fadeSpeed = 200, fadeTo = 0.5, topDistance = 30;
var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
var inside = false;
//do
$(window).scroll(function() {
position = $(window).scrollTop();
if(position > topDistance && !inside) {
//add events
topbarML();
$('#uberbar').bind('mouseenter',topbarME);
$('#uberbar').bind('mouseleave',topbarML);
inside = true;
}
else if (position < topDistance){
topbarME();
$('#uberbar').unbind('mouseenter',topbarME);
$('#uberbar').unbind('mouseleave',topbarML);
inside = false;
}
});
})();
});
Put the following code after your data is added:
final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
Partitioning data is often used for distributing load horizontally, this has performance benefit, and helps in organizing data in a logical fashion. Example: if we are dealing with a large employee
table and often run queries with WHERE
clauses that restrict the results to a particular country or department . For a faster query response Hive table can be PARTITIONED BY (country STRING, DEPT STRING)
. Partitioning tables changes how Hive structures the data storage and Hive will now create subdirectories reflecting the partitioning structure like
.../employees/country=ABC/DEPT=XYZ.
If query limits for employee from country=ABC
, it will only scan the contents of one directory country=ABC
. This can dramatically improve query performance, but only if the partitioning scheme reflects common filtering. Partitioning feature is very useful in Hive, however, a design that creates too many partitions may optimize some queries, but be detrimental for other important queries. Other drawback is having too many partitions is the large number of Hadoop files and directories that are created unnecessarily and overhead to NameNode since it must keep all metadata for the file system in memory.
Bucketing is another technique for decomposing data sets into more manageable parts. For example, suppose a table using date
as the top-level partition and employee_id
as the second-level partition leads to too many small partitions. Instead, if we bucket the employee table and use employee_id
as the bucketing column, the value of this column will be hashed by a user-defined number into buckets. Records with the same employee_id
will always be stored in the same bucket. Assuming the number of employee_id
is much greater than the number of buckets, each bucket will have many employee_id
. While creating table you can specify like CLUSTERED BY (employee_id) INTO XX BUCKETS;
where XX is the number of buckets . Bucketing has several advantages. The number of buckets is fixed so it does not fluctuate with data. If two tables are bucketed by employee_id
, Hive can create a logically correct sampling. Bucketing also aids in doing efficient map-side joins etc.
In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):
def change
add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end
The normal index would have been:
:index_studies_on_professor_id_and_user_id
The logic would be:
index
becomes idx
_id
Which usually does the job.
I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod
with [ValidateInput(false)]
and just switch off request validation for a single ActionMethod
, which is handy. And you don't need to make any changes to the web.config
file, so you can still use the .NET 4 request validation everywhere else.
e.g.
[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
// Do your own checking of value since it could contain XSS stuff!
return View();
}
Most of the answers above didn't work. I was trying to upload image to S3 bucket using react-s3 and I got this
Cross-Origin Request Blocked
error.
All you have to do is add CORS Config in s3 Bucket Go to S3 Bucket -> Persmission -> CORS Configuration And paste the below
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
Replace * with your website url. Reference : AWS CORS Settings
hi there are 2 solutions :
change the port 80 to 81 in the text file (httpd.conf) and click 127.0.0.1:81
change setting the network go to control panel--network and internet--network and sharing center
click-->local area connection select-->propertis check true in the -allow other ..... and --- allo other .....
I personnally went for:
set wrap
,set linebreak
set breakindent
set showbreak=?
.Some explanation:
wrap
option visually wraps line instead of having to scroll horizontallylinebreak
is for wrapping long lines at a specific character instead of just anywhere when the line happens to be too long, like in the middle of a word. By default, it breaks on whitespace (word separator), but you can configure it with breakat
. It also does NOT insert EOL
in the file as the OP wanted.breakat
is the character where it will visually break the line. No need to modify it if you want to break at whitespace between two words.breakindent
enables to visually indent the line when it breaks.showbreak
enables to set the character which indicates this break.See :h <keyword>
within vim for more info.
Note that you don't need to modify textwidth
nor wrapmargin
if you go this route.
Shortest answer
$"{dt:yyyy-MM-dd hh:mm:ss}"
Tests
DateTime dt1 = DateTime.Now;
Console.Write("Test 1: ");
Console.WriteLine($"{dt1:yyyy-MM-dd hh:mm:ss}"); //works
DateTime? dt2 = DateTime.Now;
Console.Write("Test 2: ");
Console.WriteLine($"{dt2:yyyy-MM-dd hh:mm:ss}"); //Works
DateTime? dt3 = null;
Console.Write("Test 3: ");
Console.WriteLine($"{dt3:yyyy-MM-dd hh:mm:ss}"); //Works - Returns empty string
Output
Test 1: 2017-08-03 12:38:57
Test 2: 2017-08-03 12:38:57
Test 3:
According to Scala's documentation:
Case classes are just regular classes that are:
- Immutable by default
- Decomposable through pattern matching
- Compared by structural equality instead of by reference
- Succinct to instantiate and operate on
Another feature of the case keyword is the compiler automatically generates several methods for us, including the familiar toString, equals, and hashCode methods in Java.
This is very good: http://simononsoftware.com/virtualenv-tutorial-part-2/
And this is a slightly more practical one: https://web.archive.org/web/20160404222648/https://iamzed.com/2009/05/07/a-primer-on-virtualenv/
one cannot use the Context
of the Service
; was able to get the (package) Context
alike:
Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
If you have a return value you need to send to the UI you can use the generic version like this:
This is being called from an MVVM ViewModel in my case.
var updateManifest = Task<ShippingManifest>.Run(() =>
{
Thread.Sleep(5000); // prove it's really working!
// GenerateManifest calls service and returns 'ShippingManifest' object
return GenerateManifest();
})
.ContinueWith(manifest =>
{
// MVVM property
this.ShippingManifest = manifest.Result;
// or if you are not using MVVM...
// txtShippingManifest.Text = manifest.Result.ToString();
System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);
}, TaskScheduler.FromCurrentSynchronizationContext());
You may also want to look at Async Http Client.
Android includes a process management system which handles the creation and destruction of activities which largely negates any benefit you'd see from manually restarting an activity. You can see more information about it at Application Fundamentals
What is good practice though is to ensure that your onPause and onStop methods release any resources which you don't need to hold on to and use onLowMemory to reduce your activities needs to the absolute minimum.
For Mojave users, I found this page very useful, particularly this suggestion:
/usr/bin/wish $(which gitk)
...without that, the window did not display correctly!
There's PDFLayoutTextStripper that was designed to keep the format of the data.
From the README:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
public class Test {
public static void main(String[] args) {
String string = null;
try {
PDFParser pdfParser = new PDFParser(new FileInputStream("sample.pdf"));
pdfParser.parse();
PDDocument pdDocument = new PDDocument(pdfParser.getDocument());
PDFTextStripper pdfTextStripper = new PDFLayoutTextStripper();
string = pdfTextStripper.getText(pdDocument);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
};
System.out.println(string);
}
}
prop_cycle
color_cycle
was deprecated in 1.5 in favor of this generalization: http://matplotlib.org/users/whats_new.html#added-axes-prop-cycle-key-to-rcparams
# cycler is a separate package extracted from matplotlib.
from cycler import cycler
import matplotlib.pyplot as plt
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b'])))
plt.plot([1, 2])
plt.plot([2, 3])
plt.plot([3, 4])
plt.plot([4, 5])
plt.plot([5, 6])
plt.show()
Also shown in the (now badly named) example: http://matplotlib.org/1.5.1/examples/color/color_cycle_demo.html mentioned at: https://stackoverflow.com/a/4971431/895245
Tested in matplotlib 1.5.1.
The answer's here, I think.
It's better if you do git rm <fileName>
, though.
git config --list
git config -l
will display your username and email together, along with other info
You should make a habit of looking at the documentation for stuff like this. It's very useful and will improve your skills very quickly. Here's the relevant bit when you do git help diff
git diff [options] [--no-index] [--] <path> <path>
The two <path>
s are what you need to change to the directories in question.
Yes you can...
PDFs have Javascript support. I needed to have auto print capabilities when a PHP-generated PDF was created and I was able to use FPDF to get it to work:
I suggest an improvement of the Adam's answer accepting HashMap as parameter
/**
* Append parameters to given url
* @param url
* @param parameters
* @return new String url with given parameters
* @throws URISyntaxException
*/
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
URI uri = new URI(url);
String query = uri.getQuery();
StringBuilder builder = new StringBuilder();
if (query != null)
builder.append(query);
for (Map.Entry<String, String> entry: parameters.entrySet())
{
String keyValueParam = entry.getKey() + "=" + entry.getValue();
if (!builder.toString().isEmpty())
builder.append("&");
builder.append(keyValueParam);
}
URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
return newUri.toString();
}
show alert box with use variable with message
<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>
Have you tried the GNU make documentation? It has a whole section about conditionals with examples.
Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.
How about:
(&(objectClass=group)(member=cn=my,ou=full,dc=domain))
(You forgot the (& ) bit in your example in the question as well).
Despite using zip(*iterable)
to transpose a nested list, you can also use the following if the nested lists vary in length:
map(None, *[(1,2,3,), (4,5,), (6,)])
results in:
[(1, 4, 6), (2, 5, None), (3, None, None)]
The first column is thus:
map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)
What I would try in this case is put this in the stylesheet
html, body{overflow:hidden;}
this way one disables the scrollbar, and as a cumulative effect they disable scrolling with the keyboard
You can use without
or pull
from Lodash:
const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
Dispatch for FTP is what Copy Web Site should have been.
This just came out but I like it a lot: Mindscape File Explorer
VisualSVN is excellent for SVN integration. Much better than Ankh (have not tried Ankh 2+ though)
SonicFileFinder for looking up files or classes quickly. Supports searching just the upper case parts of a camel-cased type name
Web Deployment Projects by Microsoft for precompiling web site projects
ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook /tmp/foo.yml -vvv
Tasks with STDOUT will then have a section:
STDOUT:
What ever was in STDOUT
Simple solution if your are using express and doing
const router = express.Router();
make sure to
module.exports = router ;
at the end of your page
Using backtick
or qx
helps, thanks everybody for the answers. However, I found that if you use backtick
or qx
, the output contains trailing newline and I need to remove that. So I used chomp
.
chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;
More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style: Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
If you wan't to animate your background using only core jQuery functionality, try this:
jQuery(".usercontent").mouseover(function() {
jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
jQuery(this).animate({
backgroundColor: 'white'
}, 'normal', 'linear', function() {
jQuery(this).css({'background':'none', backgroundColor : ''});
});
});
You can refer to this blog for printing formatted coloured text on console
https://javaforqa.wordpress.com/java-print-coloured-table-on-console/
public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");
//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases |Passed |Failed |Skipped |%n");
System.out.format("+----------------------+---------+---------+---------+%n");
String formattedMessage = "TEST_01".trim();
leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
One important difference is that both String.split() and Scanner can produce empty strings but StringTokenizer never does it.
For example:
String str = "ab cd ef";
StringTokenizer st = new StringTokenizer(str, " ");
for (int i = 0; st.hasMoreTokens(); i++) System.out.println("#" + i + ": " + st.nextToken());
String[] split = str.split(" ");
for (int i = 0; i < split.length; i++) System.out.println("#" + i + ": " + split[i]);
Scanner sc = new Scanner(str).useDelimiter(" ");
for (int i = 0; sc.hasNext(); i++) System.out.println("#" + i + ": " + sc.next());
Output:
//StringTokenizer
#0: ab
#1: cd
#2: ef
//String.split()
#0: ab
#1: cd
#2:
#3: ef
//Scanner
#0: ab
#1: cd
#2:
#3: ef
This is because the delimiter for String.split() and Scanner.useDelimiter() is not just a string, but a regular expression. We can replace the delimiter " " with " +" in the example above to make them behave like StringTokenizer.
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
print(re.match(regex, "http://www.example.com") is not None) # True
print(re.match(regex, "example.com") is not None) # False
It seems compile issue. Run project as Maven test, then Run as JUnit Test.
There is a very simple solution: http_build_query()
. It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query()
handles all the necessary escaping for you (%5B
=> [
and %5D
=> ]
), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d
.
The problem seems to be in the way how ng-model
works with input
and overwrites the name
object, making it lost for ng-repeat
.
As a workaround, one can use the following code:
<div ng-repeat="name in names">
Value: {{name}}
<input ng-model="names[$index]">
</div>
Hope it helps
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
Just a quick addition. If you're using the new analytics.js, then:
var track = function() {
ga('send', 'pageview', {'page': $location.path()});
};
Additionally one tip is that google analytics will not fire on localhost. So if you are testing on localhost, use the following instead of the default create (full documentation)
ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});
There are different ways in which properties can be overridden. Assuming you have
.left { background: blue }
e.g. any of the following would override it:
a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }
The first two “win” by selector specificity; the third one wins by !important
, a blunt instrument.
You could also organize your style sheets so that e.g. the rule
.background-none { background: none; }
wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.
These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.
P.S. I used left
and background-none
as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.
Hej this is a modified version which works OK in FF @least for me and inserts at the carets position
$.fn.extend({
insertAtCaret: function(myValue){
var obj;
if( typeof this[0].name !='undefined' ) obj = this[0];
else obj = this;
if ($.browser.msie) {
obj.focus();
sel = document.selection.createRange();
sel.text = myValue;
obj.focus();
}
else if ($.browser.mozilla || $.browser.webkit) {
var startPos = obj.selectionStart;
var endPos = obj.selectionEnd;
var scrollTop = obj.scrollTop;
obj.value = obj.value.substring(0, startPos)+myValue+obj.value.substring(endPos,obj.value.length);
obj.focus();
obj.selectionStart = startPos + myValue.length;
obj.selectionEnd = startPos + myValue.length;
obj.scrollTop = scrollTop;
} else {
obj.value += myValue;
obj.focus();
}
}
})
You should use the following:
<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>
You will need to add the FormsModule
to your app.module
in the inputs
section as follows:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule
],
..
The use of the brackets around the ngModel
are as follows:
The []
show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.
The ()
show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.
The [()]
are both (e.g. a two way binding)
See here for more information: https://angular.io/guide/template-syntax
I would also suggest replacing id="priceInput-{{orderLine.id}}"
with something like this [id]="getElementId(orderLine)"
where getElementId(orderLine)
returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1
in one place and priceInput-1
in another. (if you still need to access the input by it's Id somewhere else)
Here is more information regarding replacing ereg_replace with preg_replace
The easiest way nowadays is to use PHP configure:
# php-config --ini-dir
/usr/local/etc/php/7.4/conf.d
There's more you can find there. Example output of the --help
sub command (macOS local install):
# php-config --help
Usage: /usr/local/bin/php-config [OPTION]
Options:
--prefixUsage: /usr/local/bin/php-config [OPTION]
Options:
--prefix [/usr/local/Cellar/php/7.4.11]
--includes [-I/usr/local/Cellar/php/7.4.11/include/php - …ETC…]
--ldflags [ -L/usr/local/Cellar/krb5/1.18.2/lib -…ETC…]
--libs [ -ltidy -largon2 …ETC… ]
--extension-dir [/usr/local/Cellar/php/7.4.11/pecl/20190902]
--include-dir [/usr/local/Cellar/php/7.4.11/include/php]
--man-dir [/usr/local/Cellar/php/7.4.11/share/man]
--php-binary [/usr/local/Cellar/php/7.4.11/bin/php]
--php-sapis [ apache2handler cli fpm phpdbg cgi]
--ini-path [/usr/local/etc/php/7.4]
--ini-dir [/usr/local/etc/php/7.4/conf.d]
--configure-options [--prefix=/usr/local/Cellar/php/7.4.11 --…ETC…]
--version [7.4.11]
--vernum [70411]
Using two extension methods, this becomes very easy:
public static class Ext
{
public static void SetText(this RichTextBox richTextBox, string text)
{
richTextBox.Document.Blocks.Clear();
richTextBox.Document.Blocks.Add(new Paragraph(new Run(text)));
}
public static string GetText(this RichTextBox richTextBox)
{
return new TextRange(richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd).Text;
}
}
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
the strtok runtime function works like this
the first time you call strtok you provide a string that you want to tokenize
char s[] = "this is a string";
in the above string space seems to be a good delimiter between words so lets use that:
char* p = strtok(s, " ");
what happens now is that 's' is searched until the space character is found, the first token is returned ('this') and p points to that token (string)
in order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to your previous passed string:
p = strtok(NULL," ");
p now points to 'is'
and so on until no more spaces can be found, then the last string is returned as the last token 'string'.
more conveniently you could write it like this instead to print out all tokens:
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
puts(p);
}
EDIT:
If you want to store the returned values from strtok
you need to copy the token to another buffer e.g. strdup(p);
since the original string (pointed to by the static pointer inside strtok
) is modified between iterations in order to return the token.
The @import url("base.css");
works fine but bear in mind that every @import
statement is a new request to the server. This might not be a problem for you, but when optimal performance is required you should avoid the @import
.
Declare your TextView
not clickable / focusable by using android:clickable="false"
and android:focusable="false"
or v.setClickable(false)
and v.setFocusable(false)
. The click events should be dispatched to the TextView
's parent now.
Note:
In order to achieve this, you have to add click to its direct parent
. or set
android:clickable="false"
and android:focusable="false"
to its direct parent to pass listener to further parent.
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
Only one row code:
private static bool primeNumberTest(int i)
{
return i > 3 ? ( (Enumerable.Range(2, (i / 2) + 1).Where(x => (i % x == 0))).Count() > 0 ? false : true ) : i == 2 || i == 3 ? true : false;
}
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
A return value of the previously executed process.
10.4 Getting the return value of a program
In bash, the return value of a program is stored in a special variable called $?.
This illustrates how to capture the return value of a program, I assume that the directory dada does not exist. (This was also suggested by mike)
#!/bin/bash cd /dada &> /dev/null echo rv: $? cd $(pwd) &> /dev/null echo rv: $?
See Bash Programming Manual for more details.
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.
var keepGoing = true;
function myLoop() {
// ... Do something ...
if(keepGoing) {
setTimeout(myLoop, 1000);
}
}
function startLoop() {
keepGoing = true;
myLoop();
}
function stopLoop() {
keepGoing = false;
}
This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.
You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).
Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.
More Robust Solution
For pip3, use this:
pip3 freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip3 install -U \1/p' |sh
For pip, just remove the 3s as such:
pip freeze --local |sed -rn 's/^([^=# \t\\][^ \t=]*)=.*/echo; echo Processing \1 ...; pip install -U \1/p' |sh
OS X Oddity
OS X, as of July 2017, ships with a very old version of sed (a dozen years old). To get extended regular expressions, use -E
instead of -r
in the solution above.
Solving Issues with Popular Solutions
This solution is well designed and tested1, whereas there are problems with even the most popular solutions.
The above command uses the simplest and most portable pip syntax in combination with sed and sh to overcome these issues completely. Details of the sed operation can be scrutinized with the commented version2.
Details
[1] Tested and regularly used in a Linux 4.8.16-200.fc24.x86_64 cluster and tested on five other Linux/Unix flavors. It also runs on Cygwin64 installed on Windows 10. Testing on iOS is needed.
[2] To see the anatomy of the command more clearly, this is the exact equivalent of the above pip3 command with comments:
# Match lines from pip's local package list output
# that meet the following three criteria and pass the
# package name to the replacement string in group 1.
# (a) Do not start with invalid characters
# (b) Follow the rule of no white space in the package names
# (c) Immediately follow the package name with an equal sign
sed="s/^([^=# \t\\][^ \t=]*)=.*"
# Separate the output of package upgrades with a blank line
sed="$sed/echo"
# Indicate what package is being processed
sed="$sed; echo Processing \1 ..."
# Perform the upgrade using just the valid package name
sed="$sed; pip3 install -U \1"
# Output the commands
sed="$sed/p"
# Stream edit the list as above
# and pass the commands to a shell
pip3 freeze --local | sed -rn "$sed" | sh
[3] Upgrading a Python or PIP component that is also used in the upgrading of a Python or PIP component can be a potential cause of a deadlock or package database corruption.
The following should work as it calculates difference between DATE and UTCDATE for the server you are running and uses that offset to calculate the UTC equivalent of any date you pass to it. In my example, I am trying to convert UTC equivalent for '1-nov-2012 06:00' in Adelaide, Australia where UTC offset is -630 minutes, which when added to any date will result in UTC equivalent of any local date.
select DATEADD(MINUTE, DATEDIFF(MINUTE, GETDATE(), GETUTCDATE()), '1-nov-2012 06:00')
Many thanks for this guys.
I mangaged to get this down to one line:
var results = from p in People
where !(from e in exclusions
select e.CompositeKey).Contains(p.CompositeKey)
select p;
Thanks again everyone.
What kind of HTTP request are you making?
This is a slightly left-field answer but have you tried removing the IIS default error page for 404 to check what your API is actually returning?
I had an issue whereby I wanted a controller method to return a 404 when I POSTed the wrong id to it. I found that I was always getting the IIS 404 "File or directory not found" page rather than the HTTP response from my API. Removing the default 404 error page resolved the problem.
Different issue but you never know it may help ;)
If we are using asp.net "FileUpload" control and want to preview image before upload we can use below code.
<asp:FileUpload ID="fileUpload" runat="server" Style="border: none;" onchange="showpreview(this);" />
<img id="previewImage" src="C:\fakepath\natureImage.jpg">
<script>
function showpreview(Imagepath) {
var reader = new FileReader();
reader.onload = function (e) {
$("#previewImage").attr("src", e.target.result);
}
reader.readAsDataURL(Imagepath.files[0]);
}
</script>
the simple way I found out: add a "li" tag on the right side of an "a" tag List item
<li></span><a><span id="expand1"></span></a></li>
On CSS file create this below:
#expand1 {
padding-left: 40px;
}
The problem is that you are using getSystemResourceAsStream
. Use simply getResourceAsStream
. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.
It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.
EDIT: Normally, you would call getClass().getResourceAsStream()
to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer,
e.g.
[public] class MyClass {
static
{
...
props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
}
}
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
Sometimes if the ports are not freed even after attempting shutdown.bat what @BalusC suggested,you can kill the javaw process. Do following steps :
Enter command ps. You may see a image as follows :
See the process number of process "javaw".The process number is the rightmost number in the columns, I have highlighted in the image process number of javaw for example.
Enter command kill . javaw is killed and now you must be able to run the program.
In addition to all the great answers provided here, the official Java SE 7 programming guide has a pretty concise manual on using assert
; with several spot-on examples of when it's a good (and, importantly, bad) idea to use assertions, and how it's different from throwing exceptions.
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
Here's a random idea that utilizes (abuses?) the data model (Py3 link).
class Counter(object):
def __init__(self, val):
self.val = val
def __nonzero__(self):
self.val -= 1
return self.val >= 0
__bool__ = __nonzero__ # Alias to Py3 name to make code work unchanged on Py2 and Py3
x = Counter(5)
while x:
# Do something
pass
I wonder if there is something like this in the standard libraries?
First of all, I'd recommend using the ISO-8601 standard format for date/time - it works regardless of the language and regional settings on your SQL Server. ISO-8601 is the YYYYMMDD
format - no spaces, no dashes - just the data:
select * from tblErrorLog
where errorDate = '20081220'
Second of all, you need to be aware that SQL Server 2005 DATETIME
always includes a time. If you check for exact match with just the date part, you'll get only rows that match with a time of 0:00:00 - nothing else.
You can either use any of the recommend range queries mentioned, or in SQL Server 2008, you could use the DATE
only date time - or you could do a check something like:
select * from tblErrorLog
where DAY(errorDate) = 20 AND MONTH(errorDate) = 12 AND YEAR(errorDate) = 2008
Whichever works best for you.
If you need to do this query often, you could either try to normalize the DATETIME
to include only the date, or you could add computed columns for DAY, MONTH and YEAR:
ALTER TABLE tblErrorLog
ADD ErrorDay AS DAY(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorMonth AS MONTH(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorYear AS YEAR(ErrorDate) PERSISTED
and then you could query more easily:
select * from tblErrorLog
where ErrorMonth = 5 AND ErrorYear = 2009
and so forth. Since those fields are computed and PERSISTED, they're always up to date and always current, and since they're peristed, you can even index them if needed.
Yeah, But not in a normal way. You will have to use switch as closure.
ex:-
function test(input1, input2) {
switch (true) {
case input1 > input2:
console.log(input1 + " is larger than " + input2);
break;
case input1 < input2:
console.log(input2 + " is larger than " + input1);
default:
console.log(input1 + " is equal to " + input2);
}
}
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
also this works too
SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')
If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).
An example of a FIRST/FIRST conflict:
S -> Xb | Yc
X -> a
Y -> a
By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.
An example of a FIRST/FOLLOW conflict:
S -> AB
A -> fe | epsilon
B -> fg
By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).
Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.
run adb
command line. like this
adb devices