Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html
.
Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries
Then following codes does the job perfectly (No need of beautifulsoup and fancy html):
import pandas as pd
import requests
url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()
For future reference, this can also happen if npm is down. That's how I found this question. Wish the first npm task was a server status check so there was a clearer error message.
You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.
So you can follow these steps:
Unrelated, I'm sure, but do wrap your IDisposable
objects in using
blocks to ensure proper disposal:
using System;
using System.Net;
using System.IO;
namespace ConsoleProgram
{
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json?api_key=123";
private const string DATA = @"{""object"":{""name"":""Name""}}";
static void Main(string[] args)
{
Class1.CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(DATA);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
}
}
}
public class ParkingLot
{
Vector<ParkingSpace> vacantParkingSpaces = null;
Vector<ParkingSpace> fullParkingSpaces = null;
int parkingSpaceCount = 0;
boolean isFull;
boolean isEmpty;
ParkingSpace findNearestVacant(ParkingType type)
{
Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();
while(itr.hasNext())
{
ParkingSpace parkingSpace = itr.next();
if(parkingSpace.parkingType == type)
{
return parkingSpace;
}
}
return null;
}
void parkVehicle(ParkingType type, Vehicle vehicle)
{
if(!isFull())
{
ParkingSpace parkingSpace = findNearestVacant(type);
if(parkingSpace != null)
{
parkingSpace.vehicle = vehicle;
parkingSpace.isVacant = false;
vacantParkingSpaces.remove(parkingSpace);
fullParkingSpaces.add(parkingSpace);
if(fullParkingSpaces.size() == parkingSpaceCount)
isFull = true;
isEmpty = false;
}
}
}
void releaseVehicle(Vehicle vehicle)
{
if(!isEmpty())
{
Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();
while(itr.hasNext())
{
ParkingSpace parkingSpace = itr.next();
if(parkingSpace.vehicle.equals(vehicle))
{
fullParkingSpaces.remove(parkingSpace);
vacantParkingSpaces.add(parkingSpace);
parkingSpace.isVacant = true;
parkingSpace.vehicle = null;
if(vacantParkingSpaces.size() == parkingSpaceCount)
isEmpty = true;
isFull = false;
}
}
}
}
boolean isFull()
{
return isFull;
}
boolean isEmpty()
{
return isEmpty;
}
}
public class ParkingSpace
{
boolean isVacant;
Vehicle vehicle;
ParkingType parkingType;
int distance;
}
public class Vehicle
{
int num;
}
public enum ParkingType
{
REGULAR,
HANDICAPPED,
COMPACT,
MAX_PARKING_TYPE,
}
Detailed Answer:
It's not a full debugger, but my DP_DEBUG extensions provides some (I think) usful functionality and they work in IE, Firefox and Opera (9+).
You can "dump" visual representations of complex JavaScript objects (even system objects), do simplified logging and timing. The component provides simple methods to enable or disable it so that you can leave the debugger in place for production work if you like.
Your sort logic is wrong. This is the pseudo-code for bubble sort:
for i = 1:n,
swapped = false
for j = n:i+1,
if a[j] < a[j-1],
swap a[j,j-1]
swapped = true
? invariant: a[1..i] in final position
break if not swapped
end
See this sorting web site for good tutorial on all the various sorting methods.
function LoadData(callback)
{
alert('the data have been loaded');
callback(loadedData, currentObject);
}
One approach is to resize the UIImage in code like the following. Note: this code only scales by height, but you can easily adjust the function to scale by width as well.
let targetHeight = CGFloat(28)
let newImage = resizeImage(image: UIImage(named: "Image.png")!, targetHeight: targetHeight)
button.setImage(newImage, for: .normal)
fileprivate func resizeImage(image: UIImage, targetHeight: CGFloat) -> UIImage {
// Get current image size
let size = image.size
// Compute scaled, new size
let heightRatio = targetHeight / size.height
let newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Create new image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Return new image
return newImage!
}
It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
TransForm three formats of Data to FormData :
1. Single value like string, Number or Boolean
let sampleData = {
activityName: "Hunting3",
activityTypeID: 2,
seasonAssociated: true,
};
2. Array to be Array of Objects
let sampleData = {
activitySeason: [
{ clientId: 2000, seasonId: 57 },
{ clientId: 2000, seasonId: 57 },
],
};
3. Object holding key value pair
let sampleData = {
preview: { title: "Amazing World", description: "Here is description" },
};
The that make our life easy:
function transformInToFormObject(data) {
let formData = new FormData();
for (let key in data) {
if (Array.isArray(data[key])) {
data[key].forEach((obj, index) => {
let keyList = Object.keys(obj);
keyList.forEach((keyItem) => {
let keyName = [key, "[", index, "]", ".", keyItem].join("");
formData.append(keyName, obj[keyItem]);
});
});
} else if (typeof data[key] === "object") {
for (let innerKey in data[key]) {
formData.append(`${key}.${innerKey}`, data[key][innerKey]);
}
} else {
formData.append(key, data[key]);
}
}
return formData;
}
Example : Input Data
let sampleData = {
activityName: "Hunting3",
activityTypeID: 2,
seasonAssociated: true,
activitySeason: [
{ clientId: 2000, seasonId: 57 },
{ clientId: 2000, seasonId: 57 },
],
preview: { title: "Amazing World", description: "Here is description" },
};
Output FormData :
activityName: Hunting3
activityTypeID: 2
seasonAssociated: true
activitySeason[0].clientId: 2000
activitySeason[0].seasonId: 57
activitySeason[1].clientId: 2000
activitySeason[1].seasonId: 57
preview.title: Amazing World
preview.description: Here is description
After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.
like this:
Intent notificationIntent = new Intent(Main.this, Main.class);
notificationIntent.putExtra("sport_id", "sport"+id);
notificationIntent.putExtra("game_url", "gameURL"+id);
notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));
I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...
Well in the way this is a single page application, the solution used was:
load the content with AJAX, like any other controller, and then call:
angular.bootstrap($('#your_div_loaded_in_ajax'),["myApp","other_module"]);
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
'''my file name is
"0_male_0.wav", "0_male_2.wav"... "0_male_30.wav"...
"1_male_0.wav", "1_male_2.wav"... "1_male_30.wav"...
"8_male_0.wav", "8_male_2.wav"... "8_male_30.wav"
when I wav.read(files) I want to read them in a sorted torder, i.e., "0_male_0.wav"
"0_male_1.wav"
"0_male_2.wav" ...
"0_male_30.wav"
"1_male_0.wav"
"1_male_1.wav"
"1_male_2.wav" ...
"1_male_30.wav"
so this is how I did it.
Just take all files start with "0_*" as an example. Others you can just put it in a loop
'''
import scipy.io.wavfile as wav
import glob
from os.path import isfile, join
#get all the file names in file_names. THe order is totally messed up
file_names = [f for f in listdir(audio_folder_dir) if isfile(join(audio_folder_dir, f)) and '.wav' in f]
#find files that belongs to "0_*" group
filegroup0 = glob.glob(audio_folder_dir+'/0_*')
#now you get sorted files in group '0_*' by the last number in the filename
filegroup0 = sorted(filegroup0, key=getKey)
def getKey(filename):
file_text_name = os.path.splitext(os.path.basename(filename)) #you get the file's text name without extension
file_last_num = os.path.basename(file_text_name[0]).split('_') #you get three elements, the last one is the number. You want to sort it by this number
return int(file_last_num[2])
That's how I did my particular case. Hope it's helpful.
This error is a result of the protection level of ClassB
's constructor, not ClassB
itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal
by default. Declaring the constructor public
will fix this problem:
public ClassB() { }
* One could also say that constructors have no name, only a type; this does not change the essence of the problem.
In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone
select
ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1,
period_next_id, period_name_long
from
(
select distinct col1, period_name_long, 'X' as num
from {TABLE}
) as x
.pyc
contain the compiled bytecode of Python source files. The Python interpreter loads .pyc
files before .py
files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.
For those who are curious of sublime text editor, the unofficial-documentation may be interesting!
Suppose we have a df_data data frame as below
> df_data
ID MONTH-YEAR VALUE
1 110 JAN.2012 1000
2 111 JAN.2012 2000
3 121 FEB.2012 3000
4 131 FEB.2012 4000
5 141 MAR.2012 5000
To count number of rows in df_data grouped by MONTH-YEAR column, you can use:
> summary(df_data$`MONTH-YEAR`)
FEB.2012 JAN.2012 MAR.2012
2 2 1
summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)
You can also begin by removing all non-numerical characters and then parsing the integer:
String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);
But be warned that this only works for non-negative numbers.
Simple solution, just one line..
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
obj = Object.values(obj);
obj[1]....
we can do it with a single line of code.
user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)
You can also look at the following if you use WPF or reference System.Windows.Input
if (Keyboard.Modifiers == ModifierKeys.Shift)
The Keyboard namespace can also be used to check the pressed state of other keys with Keyboard.IsKeyDown(Key), or if you are subscribing to a KeyDownEvent or similar event, the event arguments carry a list of currently pressed keys.
dplyr
definitely does things that data.table
can not.Your point #3
dplyr abstracts (or will) potential DB interactions
is a direct answer to your own question but isn't elevated to a high enough level. dplyr
is truly an extendable front-end to multiple data storage mechanisms where as data.table
is an extension to a single one.
Look at dplyr
as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table
is, from the dplyr
perspective, one of those targets.
You will never (I hope) see a day that data.table
attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.
dplyr
can possibly do things data.table
will not or might not do as well.Based on the design of working in-memory, data.table
could have a much more difficult time extending itself into parallel processing of queries than dplyr
.
Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).
This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.
Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.
Again, no. data.table
excels at being efficient in everything it does where dplyr
gets the burden of being limited in some respects to the underlying data store and registered handlers.
This means when you run into a performance issue with data.table
you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table
then you've won yourself the joy of filing a report. This is also true when dplyr
is using data.table
as the back-end; you may see some overhead from dplyr
but odds are it is your query.
When dplyr
has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.
Also see the accepted answer to when is plyr better than data.table?
Here's a library I forked from CodeMonkeysRU.
The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.
I've also updated it to support iOS.
first create file name it as footer.xml
put this code inside it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:layout_gravity="bottom"
android:gravity="bottom"
android:layout_weight=".15"
android:orientation="horizontal"
android:background="@drawable/actionbar_dark_background_tile" >
<ImageView
android:id="@+id/lborder"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/overlay" />
<ImageView
android:id="@+id/unknown"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/notcolor" />
<ImageView
android:id="@+id/open"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/openit"
/>
<ImageView
android:id="@+id/color"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/colored" />
<ImageView
android:id="@+id/rborder"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/frames"
android:layout_weight=".14" />
</LinearLayout>
then create header.xml and put this code inside it.:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="@dimen/action_bar_height"
android:layout_gravity="top"
android:baselineAligned="true"
android:orientation="horizontal"
android:background="@drawable/actionbar_dark_background_tile" >
<ImageView
android:id="@+id/contact"
android:layout_width="37dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight=".18"
android:scaleType="fitCenter"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/logo"/>
<ImageView
android:id="@+id/share"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/share" />
<ImageView
android:id="@+id/save"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/save" />
<ImageView
android:id="@+id/set"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/set" />
<ImageView
android:id="@+id/fix"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/light" />
<ImageView
android:id="@+id/rotate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/ic_menu_rotate" />
<ImageView
android:id="@+id/stock"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/stock" />
</LinearLayout>
and then in your main_activity.xml
and put this code inside it :-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/relt"
android:background="@drawable/background" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="78dp"
android:id="@+id/down"
android:layout_alignParentBottom="true" >
<include
android:layout_width="fill_parent"
android:layout_height="78dp"
layout="@layout/footer" >
</include>
</LinearLayout>
<ImageView
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/down"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/inc"
>
</ImageView>
<include layout="@layout/header"
android:id="@+id/inc"
android:layout_width="fill_parent"
android:layout_height="50dp"></include>
happy coding :)
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
To grep for carriage return, namely the \r
character, or 0x0d
, we can do this:
grep -F $'\r' application.log
Alternatively, use printf
, or echo
, for POSIX compatibility
grep -F "$(printf '\r')" application.log
And we can use hexdump
, or less
to see the result:
$ printf "a\rb" | grep -F $'\r' | hexdump -c
0000000 a \r b \n
Regarding the use of $'\r'
and other supported characters, see Bash Manual > ANSI-C Quoting:
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard
format('LL')
Depending on what you're trying to do with it, format('LL')
could do the trick. It produces something like this:
Moment().format('LL'); // => April 29, 2016
Plug in your device and run adb shell
which will get you a command shell on your device. You don't have permission to read /storage/emulated/
but since you know it's in subdirectory 0 just go cd /storage/emulated/0
and you will be able to look around and interact as aspected.
Note: you can use adb
wirelessly as well
If you're looking to compare times, and not the dates, you could just have a standard comparison date, or match to the date you're using, as in...
DateTime time = DateTime.Parse("6/22/2009 10:00AM");
DateTime compare = DateTime.Parse(time.ToShortDateString() + " 2:00PM");
bool greater = (time > compare);
There may be better ways to to this, but keeps your dates matching.
If you are trying to bind is a Model class, you can add a new readonly property to it like:
public string FormattedPercentage
{
get
{
If(this.Percentage < 50)
return "0 %";
else
return string.Format("{0} %", this.Percentage)
}
}
Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself
You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length
parameter).
Here's your script modified for the output you're looking for:
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view
among them.
dependencies {
implementation "androidx.core:core-ktx:{latest-version}"
}
The following extension functions are handy to deal with margins:
Note: they are all extension functions of
MarginLayoutParams
, so first you need to get and cast thelayoutParams
of your view:val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)
setMargins()
extension function:Sets the margins of all axes in the ViewGroup
's MarginLayoutParams
. (The dimension has to be provided in pixels, see the last section if you want to work with dp)
inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)
updateMargins()
extension function:Updates the margins in the ViewGroup
's ViewGroup.MarginLayoutParams
.
inline fun MarginLayoutParams.updateMargins(
@Px left: Int = leftMargin,
@Px top: Int = topMargin,
@Px right: Int = rightMargin,
@Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin
params.updateMargins(left = 8)
updateMarginsRelative()
extension function:Updates the relative margins in the ViewGroup
's MarginLayoutParams
(start/end instead of left/right).
inline fun MarginLayoutParams.updateMarginsRelative(
@Px start: Int = marginStart,
@Px top: Int = topMargin,
@Px end: Int = marginEnd,
@Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin
params.updateMargins(start = 8)
The following extension properties are handy to get the current margins:
inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
dp
instead of px
:If you want to work with dp
(density-independent pixels) instead of px
, you will need to convert them first. You can easily do that with the following extension property:
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
Then you can call the previous extension functions like:
params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp
Old answer:
In Kotlin you can declare an extension function like:
fun View.setMargins(
leftMarginDp: Int? = null,
topMarginDp: Int? = null,
rightMarginDp: Int? = null,
bottomMarginDp: Int? = null
) {
if (layoutParams is ViewGroup.MarginLayoutParams) {
val params = layoutParams as ViewGroup.MarginLayoutParams
leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
topMarginDp?.run { params.topMargin = this.dpToPx(context) }
rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
requestLayout()
}
}
fun Int.dpToPx(context: Context): Int {
val metrics = context.resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}
Then you can call it like:
myView1.setMargins(8, 16, 34, 42)
Or:
myView2.setMargins(topMarginDp = 8)
I see only two options:
This is, I believe, a general solution, though I tested it using IBM Informix Dynamic Server 11.50.FC3. The following query:
SELECT grade,
ROUND(100.0 * grade_sum / (SELECT COUNT(*) FROM grades), 2) AS pct_of_grades
FROM (SELECT grade, COUNT(*) AS grade_sum
FROM grades
GROUP BY grade
)
ORDER BY grade;
gives the following output on the test data shown below the horizontal rule. The ROUND
function may be DBMS-specific, but the rest (probably) is not. (Note that I changed 100 to 100.0 to ensure that the calculation occurs using non-integer - DECIMAL, NUMERIC - arithmetic; see the comments, and thanks to Thunder.)
grade pct_of_grades
CHAR(1) DECIMAL(32,2)
A 32.26
B 16.13
C 12.90
D 12.90
E 9.68
F 16.13
CREATE TABLE grades
(
id VARCHAR(10) NOT NULL,
grade CHAR(1) NOT NULL CHECK (grade MATCHES '[ABCDEF]')
);
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1002', 'B');
INSERT INTO grades VALUES('1003', 'F');
INSERT INTO grades VALUES('1004', 'C');
INSERT INTO grades VALUES('1005', 'D');
INSERT INTO grades VALUES('1006', 'A');
INSERT INTO grades VALUES('1007', 'F');
INSERT INTO grades VALUES('1008', 'C');
INSERT INTO grades VALUES('1009', 'A');
INSERT INTO grades VALUES('1010', 'E');
INSERT INTO grades VALUES('1001', 'A');
INSERT INTO grades VALUES('1012', 'F');
INSERT INTO grades VALUES('1013', 'D');
INSERT INTO grades VALUES('1014', 'B');
INSERT INTO grades VALUES('1015', 'E');
INSERT INTO grades VALUES('1016', 'A');
INSERT INTO grades VALUES('1017', 'F');
INSERT INTO grades VALUES('1018', 'B');
INSERT INTO grades VALUES('1019', 'C');
INSERT INTO grades VALUES('1020', 'A');
INSERT INTO grades VALUES('1021', 'A');
INSERT INTO grades VALUES('1022', 'E');
INSERT INTO grades VALUES('1023', 'D');
INSERT INTO grades VALUES('1024', 'B');
INSERT INTO grades VALUES('1025', 'A');
INSERT INTO grades VALUES('1026', 'A');
INSERT INTO grades VALUES('1027', 'D');
INSERT INTO grades VALUES('1028', 'B');
INSERT INTO grades VALUES('1029', 'A');
INSERT INTO grades VALUES('1030', 'C');
INSERT INTO grades VALUES('1031', 'F');
Semantically, both versions of delete operator in C++ can "eat" any pointer; however, if a pointer to a single object is given to delete[]
, then UB will result, meaning anything may happen, including a system crash or nothing at all.
C++ requires the programmer to choose the proper version of the delete operator depending on the subject of deallocation: array or single object.
If the compiler could automatically determine whether a pointer passed to the delete operator was a pointer array, then there would be only one delete operator in C++, which would suffice for both cases.
Put the image — let's say it's width is 140px — inside of a link:
<a><img src='image link' style='width: 140px'></a>
Next, put the caption in a and give it a width less than your image, while centering it:
<a>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.
<a style='text-decoration: none; color: orange;'>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html
I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,
return File(returnFilePath, contentType, fileName);
would give the error in mobile safari, where as
return File(returnFilePath, contentType);
would not.
I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.
Here's why you saw the menu with the code you listed in your onClick
method:
You were creating an Intent with the constructor that takes a string for the action parameter of the Intent
's IntentFilter
. You passed "android.intent.action.MAIN"
as the argument to that constructor, which specifies that the Intent
can be satisfied by any Activity
with an IntentFilter including <action="android.intent.action.MAIN">
.
When you called startActivity
with that Intent
, you effectively told the Android OS to go find an Activity
(in any app installed on the system) that specifies the android.intent.action.MAIN
action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity
with an IntentFilter
including the "android.intent.action.MAIN"
action), the OS presents a menu to let the user choose which app to use.
As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button
's onClick()
method contains only a call to finish()
then you should most likely remove the Button
from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).
If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity
after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP
which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:
btnReturn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
)};
Use explode() or preg_split() function to split the string in php with given delimiter
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
text = 'I want to find a string between two substrings'
left = 'find a '
right = 'between two'
print(text[text.index(left)+len(left):text.index(right)])
Gives
string
public static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
I received this error after I moved from a 5s to a 6s. I recovered the new 6s from a backup of the old iPhone. Because of this on the new iPhone the old app was installed.
The old app did not show up in the 6s "Installed Apps" list! I manually deleted this old app from the 6s and everything was fine.
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3
is the index of the option you want.
What about something like this (might have rounding errors and negative-value issues that need debugging, left as an exercise for the reader):
printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));
It's slightly programmatic but at least it doesn't make you do any string manipulation.
var start = +new Date();
var counter = 0;
for(var i = 1; i < LIMIT; i++){
++counter;
db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
if( err || !saved ) console.log("Error");
else console.log("Saved");
if (--counter === 0)
{
var end = +new Date();
console.log("all users saved in " + (end-start) + " milliseconds");
}
});
}
I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.
Being as it is a setting that is stored per-user, the session is an appropriate place to store the informtion.
I would change your controller to take the culture string as a parameter, rather than having a different action method for each potential culture. Adding a link to the page is easy, and you shouldn't need to write the same code repeatedly any time a new culture is required.
public class CultureController : Controller
{
public ActionResult SetCulture(string culture)
{
HttpContext.Session["culture"] = culture
return RedirectToAction("Index", "Home");
}
}
<li><%= Html.ActionLink("French", "SetCulture", new {controller = "Culture", culture = "fr-FR"})%></li>
<li><%= Html.ActionLink("Spanish", "SetCulture", new {controller = "Culture", culture = "es-ES"})%></li>
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">
$(function() {
$(".update").bind("click", // bind the click event to a div
function() {
var selectOption = $('.selDiv').children('.opts') ;
var _this = $(this).next().children(".opts") ;
$(selectOption).find("option[index='0']").attr("selected","selected");
// $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
// $(selectOption).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[value='DEFAULT']").attr("selected","selected");
// $(_this).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[index='0']").attr("selected","selected");
}); // END Bind
}); // End eventlistener
</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
</body>
</html>
The issue is that the Android User-Agent is a general User-Agent and there is no difference between tablet Android and mobile Android.
This is incorrect. Mobile Android has "Mobile" string in the User-Agent header. Tablet Android does not.
But it is worth mentioning that there are quite a few tablets that report "Mobile" Safari in the userAgent and the latter is not the only/solid way to differentiate between Mobile and Tablet.
You're using jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead you can use on method and bind the JavaScript load event:
$(window).on('load', function () {
alert("Window Loaded");
});
I tried almost all the options above, none of them worked for my scenario. Finally I was forced to uninstall IIS Express, re-start the machine, and install the same version again from Microsoft.
Anyway thanks for all the suggestions above.
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
You can use varargs for optional parameters:
public class Booyah {
public static void main(String[] args) {
woohoo(1);
woohoo(2, 3);
}
static void woohoo(int required, Integer... optional) {
Integer lala;
if (optional.length == 1) {
lala = optional[0];
} else {
lala = 2;
}
System.out.println(required + lala);
}
}
Also it's important to note the use of Integer
over int
. Integer
is a wrapper around the primitive int
, which allows one to make comparisons with null
as necessary.
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable
object associated with a particular resource ID
for the given screen density/theme
. Calling the deprecated
getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
If you need wait until the ajax call is completed all do you need is make your call synchronously.
A view is a better approach but since hql typically returns a List or Set... you can do list_1.addAll(list_2). Totally sucks compared to a union but should work.
I tried adding dynamically created ListItem and assigning the selected value.
foreach(var item in yourListFromDB)
{
ListItem listItem = new ListItem();
listItem.Text = item.name;
listItem.Value = Convert.ToString(item.value);
listItem.Selected=item.isSelected;
checkedListBox1.Items.Add(listItem);
}
checkedListBox1.DataBind();
avoid using binding the DataSource as it will not bind the checked/unchecked from DB.
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
This happens because the current account you have used to log in probably has very limited priviledges.
To fix this problem, you can change your the AllowNoPassword config setting to false in config.inc.php
. You may also force the authentication to use the config file and specify the default username and password .
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password
After this, the PhPMyAdmin login page should show up when you refresh the page. You can then log in with the default root password.
More details can be found on this post ..
scrollHeight
is a regular javascript property so you don't need jQuery.
var test = document.getElementById("foo").scrollHeight;
If your published app has no admob and its settings in Google Developer Console (called "Pricing and Distribution") "CONTAINS ADS" is uncheched. Always develop with test id with logcat output.
You can write a generic function to do this...
var numberFormat = function(number, width) {
return new Array(+width + 1 - (number + '').length).join('0') + number;
}
That way, it's not a problem to deal with any arbitrarily width.
Place the cursor next to an opening or closing brace and punch Ctrl + Shift + P to find the matching brace. If Eclipse can't find one you'll get a "No matching bracket found" message.
edit: as mentioned by Romaintaz below, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.
As cardern has said list will do the job.
Here is how you can use a named range.
Select your range and enter a new name:
Select your cell that you want a drop down to be in and goto data tab -> data validation.
Select 'List' from the 'Allow' Drop down menu.
Enter your named range like this:
Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
You can use boolean indexing
:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
A Sales
0 3 10
1 4 20
2 7 30
3 6 40
4 1 50
s = 30
df1 = df[df['Sales'] >= s]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
df2 = df[df['Sales'] < s]
print (df2)
A Sales
0 3 10
1 4 20
It's also possible to invert mask
by ~
:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
print (df2)
A Sales
0 3 10
1 4 20
print (mask)
0 False
1 False
2 True
3 True
4 True
Name: Sales, dtype: bool
print (~mask)
0 True
1 True
2 False
3 False
4 False
Name: Sales, dtype: bool
Angular 7,8 fix is in app.module.ts
import {APP_BASE_HREF} from '@angular/common';
inside @NgModule add
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)
The Numpy histogram
function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.
In this example:
np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]
) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5
, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.
The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1
values), and bin "2 to 3" contains one occurrence (the 2
). These results are in the first item in the returned tuple: array([0, 2, 1])
.
Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:
You can plot this directly with Matplotlib (its hist
function also returns the bins and the values):
>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()
If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:
public class GameViewModel
{
public virtual Ship Ship { get; set; }
public virtual GamePlayer GamePlayer { get; set; }
}
Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:
GameViewModel PlayerStats = new GameViewModel();
GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();
[code to check if results]
//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;
Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.
On Ubuntu, after creating localhost and '%' versions of the user, and granting appropriate access to database.tables for both, I had to comment out the 'bind-address' in /etc/mysql/mysql.conf.d/mysql.cnf and restart mysql as sudo.
you can measure how long your program works. The following functions help measure the CPU time since the start of the program:
my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics
so you can add this line of code after your algorithm
cout << (double)clock() / CLOCKS_PER_SEC ;
Expected Output: the output representing the number of clock ticks per second
Prerequisites to execute this command -
pip (recursive acronym of Pip Installs Packages) is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI).
sudo apt-get install python-pip
Install Virtual Environment. Used to create virtual environment, to install packages and dependencies of multiple projects isolated from each other.
sudo pip install virtualenv
Install virtual environment wrapper About virtual env wrapper
sudo pip install virtualenvwrapper
After Installing prerequisites you need to bring virtual environment wrapper into action to create virtual environment. Following are the steps -
set virtual environment directory in path variable-
export WORKON_HOME=(directory you need to save envs)
source /usr/local/bin/virtualenvwrapper.sh -p $WORKON_HOME
As mentioned by @Mike, source `which virtualenvwrapper.sh` or which virtualenvwrapper.sh
can used to locate virtualenvwrapper.sh file.
It's best to put above two lines in ~/.bashrc to avoid executing the above commands every time you open new shell. That's all you need to create environment using mkvirtualenv
Points to keep in mind -
Not exactly a DBMS-agnostic solution, but at least your client code won't see the difference...
Create another table T with just one row and one integer field N1, and create INSERT TRIGGER that just executes:
UPDATE T SET N = N + 1
Also create a DELETE TRIGGER that executes:
UPDATE T SET N = N - 1
A DBMS worth its salt will guarantee the atomicity of the operations above2, and N will contain the accurate count of rows at all times, which is then super-quick to get by simply:
SELECT N FROM T
While triggers are DBMS-specific, selecting from T isn't and your client code won't need to change for each supported DBMS.
However, this can have some scalability issues if the table is INSERT or DELETE-intensive, especially if you don't COMMIT immediately after INSERT/DELETE.
1 These names are just placeholders - use something more meaningful in production.
2 I.e. N cannot be changed by a concurrent transaction between reading and writing to N, as long as both reading and writing are done in a single SQL statement.
The FacetGrid
plot does produce pretty small labels. While @paul-h has described the use of sns.set
as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale
setting for all plots.
You could use the seaborn.plotting_context
to change the settings for just the current plot:
with sns.plotting_context(font_scale=1.5):
sns.factorplot(x, y ...)
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Add Section</p>
<label>First Number:</label>
<input id="txt1" type="text"/><br />
<label>Second Number:</label>
<input id="txt2" type="text"/><br />
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
Here's an updated answer, as of Sept. 2013. This took me awhile to figure out.
Go to the Admin tab.
In the middle column, select the web property that you want to delete from the dropdown.
It will warn you that you're about to delete all of the data associated with this property. If you're sure, confirm.
Done!
you cant do this. Use a custom popup. Something like with the help of jQuery UI or jQuery BOXY.
for jQuery UI http://jqueryui.com/demos/dialog/
for jQuery BOXY http://onehackoranother.com/projects/jquery/boxy/
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
above line was giving me an error. So I wrote down in below way which is working fine for me.
<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>
Maybe someone else might get same error. Look at this guys!
According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.
The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.
You can take the first string, replace all the @
with vs
using str_replace
, then explode on vs
or vice versa.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$max_no_img=4; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))
{
//echo $key;
//echo "<br>";
//echo $value;
//echo "<br>";
if(!empty($value)){ // this will check if any blank field is entered
$filename =rand(1,100000).$value; // filename stores the value
$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "upload/$filename"; // upload directory path is set
//echo $_FILES['images']['type'][$key]; // uncomment this line if you want to display the file type
//echo "<br>"; // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add);
echo $add;
// upload the file to the server
chmod("$add",0777); // set permission to the file.
}
}
?>
</body>
</html>
use following LoadType method to use System.Reflection to load all registered(GAC) and referenced assemblies and check for typeName
public Type[] LoadType(string typeName)
{
return LoadType(typeName, true);
}
public Type[] LoadType(string typeName, bool referenced)
{
return LoadType(typeName, referenced, true);
}
private Type[] LoadType(string typeName, bool referenced, bool gac)
{
//check for problematic work
if (string.IsNullOrEmpty(typeName) || !referenced && !gac)
return new Type[] { };
Assembly currentAssembly = Assembly.GetExecutingAssembly();
List<string> assemblyFullnames = new List<string>();
List<Type> types = new List<Type>();
if (referenced)
{ //Check refrenced assemblies
foreach (AssemblyName assemblyName in currentAssembly.GetReferencedAssemblies())
{
//Load method resolve refrenced loaded assembly
Assembly assembly = Assembly.Load(assemblyName.FullName);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
}
if (gac)
{
//GAC files
string gacPath = Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\assembly";
var files = GetGlobalAssemblyCacheFiles(gacPath);
foreach (string file in files)
{
try
{
//reflection only
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(file);
//Check if type is exists in assembly
var type = assembly.GetType(typeName, false, true);
if (type != null && !assemblyFullnames.Contains(assembly.FullName))
{
types.Add(type);
assemblyFullnames.Add(assembly.FullName);
}
}
catch
{
//your custom handling
}
}
}
return types.ToArray();
}
public static string[] GetGlobalAssemblyCacheFiles(string path)
{
List<string> files = new List<string>();
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles("*.dll"))
{
files.Add(fi.FullName);
}
foreach (DirectoryInfo diChild in di.GetDirectories())
{
var files2 = GetGlobalAssemblyCacheFiles(diChild.FullName);
files.AddRange(files2);
}
return files.ToArray();
}
Math.Floor(123456.646 * 100) / 100 Would return 123456.64
location.href = "Pagename.html";
The abort
function does this. For example:
abort("Message goes here")
Note: the abort
message will be written to STDERR
as opposed to puts
which will write to STDOUT
.
I just discovered that tabulate has a HTML option and is rather simple to use.
Quite similar to Wayne Werner's answer:
from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
["Earth",6371,5973.6],
["Moon",1737,73.5],
["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))
Still looking for something simple to use to create more complex table layouts like with latex syntax and formatting to merge cells and do variable substitution in a notebook:
Allow references to Python variables in Markdown cells #2958
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
Taken from @J-Rou's comment
simple answer:
let str = 'this is string, length is >26';_x000D_
_x000D_
console.log([...str]);
_x000D_
For IE11 example (browser type=Trident version=7.0):
image.style.transform = "rotate(270deg)";
cat /proc/meminfo | grep MemTotal
or free gives you the exact amount of RAM your server has. This is not "available memory".
I guess your issue comes up when you have a VM and you would like to calculate the full amount of memory hosted by the hypervisor but you will have to log into the hypervisor in that case.
cat /proc/meminfo | grep MemTotal
is equivalent to
getconf -a | grep PAGES | awk 'BEGIN {total = 1} {if (NR == 1 || NR == 3) total *=$NF} END {print total / 1024" kB"}'
I ended up using this solution.
decimal weeklyWage;
decimal.TryParse(items[2],NumberStyles.Any, new NumberFormatInfo() { NumberDecimalSeparator = "."}, out weeklyWage);
The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
In the init method
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
In iOS 6 the delegate function was deprecated. The new delegate is
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Therefore to get the new position use
[locations lastObject]
In iOS 8 the permission should be explicitly asked before starting to update location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
You also have to add a string for the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
keys to the app's Info.plist. Otherwise calls to startUpdatingLocation
will be ignored and your delegate will not receive any callback.
And at the end when you are done reading location call stopUpdating location at suitable place.
[locationManager stopUpdatingLocation];
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
The sscanf() solution is better in terms of code lines. My answer here is a user-build function that does almost the same as sscanf(). Stores the converted number in a pointer and returns a value called "val". If val comes out as zero, then the input is in unsupported format, hence conversion failed. Hence, use the pointer value only when val is non-zero.
It works only if the input is in base-10 form.
#include <stdio.h>
#include <string.h>
int CONVERT_3(double* Amt){
char number[100];
// Input the Data
printf("\nPlease enter the amount (integer only)...");
fgets(number,sizeof(number),stdin);
// Detection-Conversion begins
int iters = strlen(number)-2;
int val = 1;
int pos;
double Amount = 0;
*Amt = 0;
for(int i = 0 ; i <= iters ; i++ ){
switch(i){
case 0:
if(number[i]=='+'){break;}
if(number[i]=='-'){val = 2; break;}
if(number[i]=='.'){val = val + 10; pos = 0; break;}
if(number[i]=='0'){Amount = 0; break;}
if(number[i]=='1'){Amount = 1; break;}
if(number[i]=='2'){Amount = 2; break;}
if(number[i]=='3'){Amount = 3; break;}
if(number[i]=='4'){Amount = 4; break;}
if(number[i]=='5'){Amount = 5; break;}
if(number[i]=='6'){Amount = 6; break;}
if(number[i]=='7'){Amount = 7; break;}
if(number[i]=='8'){Amount = 8; break;}
if(number[i]=='9'){Amount = 9; break;}
default:
switch(number[i]){
case '.':
val = val + 10;
pos = i;
break;
case '0':
Amount = (Amount)*10;
break;
case '1':
Amount = (Amount)*10 + 1;
break;
case '2':
Amount = (Amount)*10 + 2;
break;
case '3':
Amount = (Amount)*10 + 3;
break;
case '4':
Amount = (Amount)*10 + 4;
break;
case '5':
Amount = (Amount)*10 + 5;
break;
case '6':
Amount = (Amount)*10 + 6;
break;
case '7':
Amount = (Amount)*10 + 7;
break;
case '8':
Amount = (Amount)*10 + 8;
break;
case '9':
Amount = (Amount)*10 + 9;
break;
default:
val = 0;
}
}
if( (!val) | (val>20) ){val = 0; break;}// val == 0
}
if(val==1){*Amt = Amount;}
if(val==2){*Amt = 0 - Amount;}
if(val==11){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = Amount/den;
}
if(val==12){
int exp = iters - pos;
long den = 1;
for( ; exp-- ; ){
den = den*10;
}
*Amt = 0 - (Amount/den);
}
return val;
}
int main(void) {
double AM = 0;
int c = CONVERT_3(&AM);
printf("\n\n%d %lf\n",c,AM);
return(0);
}
Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/
Have you enabled 'unknown sources' from security and restrictions settings?
I've started to think that using the 'iframe' for Ajax style upload might be a much better choice for my situation until HTML5 comes full circle and I don't have to support legacy browsers in my app!
The normal way to plot plots with points in different colors in matplotlib is to pass a list of colors as a parameter.
E.g.:
import matplotlib.pyplot
matplotlib.pyplot.scatter([1,2,3],[4,5,6],color=['red','green','blue'])
When you have a list of lists and you want them colored per list. I think the most elegant way is that suggesyted by @DSM, just do a loop making multiple calls to scatter.
But if for some reason you wanted to do it with just one call, you can make a big list of colors, with a list comprehension and a bit of flooring division:
import matplotlib
import numpy as np
X = [1,2,3,4]
Ys = np.array([[4,8,12,16],
[1,4,9,16],
[17, 10, 13, 18],
[9, 10, 18, 11],
[4, 15, 17, 6],
[7, 10, 8, 7],
[9, 0, 10, 11],
[14, 1, 15, 5],
[8, 15, 9, 14],
[20, 7, 1, 5]])
nCols = len(X)
nRows = Ys.shape[0]
colors = matplotlib.cm.rainbow(np.linspace(0, 1, len(Ys)))
cs = [colors[i//len(X)] for i in range(len(Ys)*len(X))] #could be done with numpy's repmat
Xs=X*nRows #use list multiplication for repetition
matplotlib.pyplot.scatter(Xs,Ys.flatten(),color=cs)
cs = [array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
...
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00])]
My solution
ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
I have personally found pywinrm
library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.
This is how I would write using more functional way
. Here is the code:
new List<Money>()
{
new Money() { Amount = 10, Type = "US"},
new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});
top, parent, opener (as well as window, self, and iframe) are all window objects.
window.opener
-> returns the window that opens or launches the current popup window.window.top
-> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.window.parent
-> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or selfSimilar Question here
I'll repost my response and propose a merge:
Output UTC seems to be the subject of some confusion -- people seem to gravitate toward moment.js.
Borrowing from this answer, you could do something like this (i.e. use a convert function that creates the date with the UTC constructor) without moment.js:
controller
var app1 = angular.module('app1',[]);
app1.controller('ctrl',['$scope',function($scope){
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
}]);
template
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
here's plunker to play with it
Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.
Try the following in viewDidLoad
self.navigationItem.title = "Your Title"
I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.
=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))
Unless you can get PHP to label that element with a class you are better to use jQuery.
jQuery(document).ready(function () {
$count = jQuery("ul li").size() - 1;
alert($count);
jQuery("ul li:nth-child("+$count+")").css("color","red");
});
Local variables are located on the stack. Heap space is occupied by objects.
You can use the -Xmx
option.
Basically heap space is used up everytime you allocate a new object with new
and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.
Just came across the same problem on a freshly installed CentOS 6.4 64-bit machine. A single yum command will fix this plus 99% of similar problems:
yum groupinstall "Compatibility libraries"
Either prefix this with 'sudo' or run as root, whichever works best for you.
Well, doing using an regular expression will be a lot easier:
mainUrl = "http://www.mywebsite.com/mypath/to/folder";
urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(mainUrl);
host = Fragment[1]; // www.mywebsite.com
Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found
if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10")
will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])
For MySql you can use LIMIT like below (Example shows in PHP)
$sql = "SELECT column_name FROM table_name WHERE column_name = 'your_value' LIMIT 1";
$result = $conn->query($sql);
if ($result -> num_rows > 0) {
echo "Value exists" ;
} else {
echo "Value not found";
}
If you remove directives attribute it should work.
@Component({
selector: 'parent',
template: `
<h1>Parent Component</h1>
<child></child>
`
})
export class ParentComponent{}
@Component({
selector: 'child',
template: `
<h4>Child Component</h4>
`
})
export class ChildComponent{}
Directives are like components but they are used in attributes. They also have a declarator @Directive
. You can read more about directives Structural Directives and Attribute Directives.
There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.
A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.
Also if you are open the glossary you can find that components are also directives.
Directives fall into one of the following categories:
Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.
Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.
Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.
The difference that components have a template. See Angular Architecture overview.
A directive is a class with a
@Directive
decorator. A component is a directive-with-a-template; a@Component
decorator is actually a@Directive
decorator extended with template-oriented features.
The @Component
metadata doesn't have directives
attribute. See Component decorator.
Here you have an example of a Dockerfile that runs nginx. As mentionned by Charles, it uses the daemon off
configuration:
https://github.com/darron/docker-nginx-php5/blob/master/Dockerfile#L17
In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.
select standard_hash('foo', 'MD5') from dual;
The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:
select rawtohex(
DBMS_CRYPTO.Hash (
UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
2)
) from dual;
Output:
ACBD18DB4CC2F85CEDEF654FCCC4A4D8
Add a lower function call if needed. More on DBMS_CRYPTO.
The problem here is your user doesn't have proper rights/permissions to open the file this means that you'd need to grant some administrative privileges to your python ide before you run that command.
As you are a windows user you just need to right click on python ide => select option 'Run as Administrator' and then run your command.
And if you are using the command line to run the codes, do the same open the command prompt with admin rights. Hope it helps
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
The problem with scrolling and text wrapping is that this code is assuming that both the width and the height are set to wrap_content
. However, the LayoutManager
needs to know that the horizontal width is constrained. So instead of creating your own widthSpec
for each child view, just use the original widthSpec
:
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(widthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
Look in the Python re documentation for lookaheads (?=...)
and lookbehinds (?<=...)
-- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
<!--This yearpicker development from Zlatko Borojevic_x000D_
html elemnts can generate with java function_x000D_
and then declare as custom type for easy use in all html documents _x000D_
For this version for implementacion in your document can use:_x000D_
1. Save this code for example: "yearonly.html"_x000D_
2. creaate one div with id="yearonly"_x000D_
3. Include year picker with function: $("#yearonly").load("yearonly.html"); _x000D_
_x000D_
<div id="yearonly"></div>_x000D_
<script>_x000D_
$("#yearonly").load("yearonly.html"); _x000D_
</script>_x000D_
-->_x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<meta name="viewport" content="text-align:center; width=device-width, initial-scale=1.0">_x000D_
<html>_x000D_
<body>_x000D_
<style>_x000D_
.ydiv {_x000D_
border:solid 1px;_x000D_
width:200px;_x000D_
//height:150px;_x000D_
background-color:#D8D8D8;_x000D_
display:none;_x000D_
position:absolute;_x000D_
top:40px;_x000D_
}_x000D_
_x000D_
.ybutton {_x000D_
_x000D_
border: none;_x000D_
width:35px;_x000D_
height:35px;_x000D_
background-color:#D8D8D8;_x000D_
font-size:100%;_x000D_
}_x000D_
_x000D_
.yhr {_x000D_
background-color:black;_x000D_
color:black;_x000D_
height:1px">_x000D_
}_x000D_
_x000D_
.ytext {_x000D_
border:none;_x000D_
text-align:center;_x000D_
width:118px;_x000D_
font-size:100%;_x000D_
background-color:#D8D8D8;_x000D_
font-weight:bold;_x000D_
_x000D_
}_x000D_
</style>_x000D_
<p>_x000D_
<!-- input text for display result of yearpicker -->_x000D_
<input type = "text" id="yeardate"><button style="width:21px;height:21px"onclick="enabledisable()">V</button></p>_x000D_
_x000D_
<!-- yearpicker panel for change only year-->_x000D_
<div class="ydiv" id = "yearpicker">_x000D_
<button class="ybutton" style="font-weight:bold;"onclick="changedecade('back')"><</button>_x000D_
_x000D_
<input class ="ytext" id="dec" type="text" value ="2018" >_x000D_
_x000D_
<button class="ybutton" style="font-weight:bold;" onclick="changedecade('next')">></button>_x000D_
<hr></hr>_x000D_
_x000D_
_x000D_
_x000D_
<!-- subpanel with one year 0-9 -->_x000D_
<button class="ybutton" onclick="yearone = 0;setyear()">0</button>_x000D_
<button class="ybutton" onclick="yearone = 1;setyear()">1</button>_x000D_
<button class="ybutton" onclick="yearone = 2;setyear()">2</button>_x000D_
<button class="ybutton" onclick="yearone = 3;setyear()">3</button>_x000D_
<button class="ybutton" onclick="yearone = 4;setyear()">4</button><br>_x000D_
<button class="ybutton" onclick="yearone = 5;setyear()">5</button>_x000D_
<button class="ybutton" onclick="yearone = 6;setyear()">6</button>_x000D_
<button class="ybutton" onclick="yearone = 7;setyear()">7</button>_x000D_
<button class="ybutton" onclick="yearone = 8;setyear()">8</button>_x000D_
<button class="ybutton" onclick="yearone = 9;setyear()">9</button>_x000D_
</div>_x000D_
<!-- end year panel -->_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
var date = new Date();_x000D_
var year = date.getFullYear(); //get current year_x000D_
//document.getElementById("yeardate").value = year;// can rem if filing text from database_x000D_
_x000D_
var yearone = 0;_x000D_
_x000D_
function changedecade(val1){ //change decade for year_x000D_
_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
if (val1 == "next"){_x000D_
document.getElementById('dec').value = x + 10;_x000D_
}else{_x000D_
document.getElementById('dec').value = x - 10;_x000D_
}_x000D_
}_x000D_
_x000D_
function setyear(){ //set full year as sum decade and one year in decade_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
var y = parseFloat(yearone);_x000D_
_x000D_
var suma = x + y;_x000D_
var d = new Date();_x000D_
d.setFullYear(suma);_x000D_
var year = d.getFullYear();_x000D_
document.getElementById("dec").value = year;_x000D_
document.getElementById("yeardate").value = year;_x000D_
document.getElementById("yearpicker").style.display = "none";_x000D_
yearone = 0;_x000D_
}_x000D_
_x000D_
function enabledisable(){ //enable/disable year panel_x000D_
if (document.getElementById("yearpicker").style.display == "block"){_x000D_
document.getElementById("yearpicker").style.display = "none";}else{_x000D_
document.getElementById("yearpicker").style.display = "block";_x000D_
}_x000D_
_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Here is a solution based on the powerful but poorly documented logging.config.dictConfig
method.
Instead of sending every log message to stdout
, it sends messages with log level ERROR
and higher to stderr
and everything else to stdout
.
This can be useful if other parts of the system are listening to stderr
or stdout
.
import logging
import logging.config
import sys
class _ExcludeErrorsFilter(logging.Filter):
def filter(self, record):
"""Only returns log messages with log level below ERROR (numeric value: 40)."""
return record.levelno < 40
config = {
'version': 1,
'filters': {
'exclude_errors': {
'()': _ExcludeErrorsFilter
}
},
'formatters': {
# Modify log message format here or replace with your custom formatter class
'my_formatter': {
'format': '(%(process)d) %(asctime)s %(name)s (line %(lineno)s) | %(levelname)s %(message)s'
}
},
'handlers': {
'console_stderr': {
# Sends log messages with log level ERROR or higher to stderr
'class': 'logging.StreamHandler',
'level': 'ERROR',
'formatter': 'my_formatter',
'stream': sys.stderr
},
'console_stdout': {
# Sends log messages with log level lower than ERROR to stdout
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'my_formatter',
'filters': ['exclude_errors'],
'stream': sys.stdout
},
'file': {
# Sends all log messages to a file
'class': 'logging.FileHandler',
'level': 'DEBUG',
'formatter': 'my_formatter',
'filename': 'my.log',
'encoding': 'utf8'
}
},
'root': {
# In general, this should be kept at 'NOTSET'.
# Otherwise it would interfere with the log levels set for each handler.
'level': 'NOTSET',
'handlers': ['console_stderr', 'console_stdout', 'file']
},
}
logging.config.dictConfig(config)
without disabling the selected value on submitting..
$('#selectID option:not(:selected)').prop('disabled', true);
If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);
It works for me..
If you have array of arrays and want to concat the elements into a single array, try the following code (Requires ES2015):
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = [];
for (let arr of arrOfArr) {
newArr.push(...arr);
}
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
Or if you're into functional programming
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = arrOfArr.reduce((result,current)=>{
result.push(...current);
return result;
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
Or even better with ES5 syntax, without the spread operator
var arrOfArr = [[1,2,3,4],[5,6,7,8]];
var newArr = arrOfArr.reduce((result,current)=>{
return result.concat(current);
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
This way is handy if you do not know the no. of arrays at the code time.
This works:
from datetime import date
today =date.today()
Output in this time: 2020-08-29
Additional:
this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)
Please try the below XAML snippet:
<Button Width="300" Height="50">
<StackPanel Orientation="Horizontal">
<Image Source="Pictures/img.jpg" Width="20" Height="20"/>
<TextBlock Text="Blablabla" VerticalAlignment="Center" />
</StackPanel>
</Button>
In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
For virtualenv to install all files in the requirements.txt file.
pip install -r requirements.txt
in your shellYour mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
You can use usort
with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold
by default, but they are marked up using <h1>
–<h6>
, not <strong>
or <b>
.
In HTML5, you use <strong>
to indicate important parts of a sentence, for example:
<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.
And you use <em>
to indicate linguistic stress, for example:
<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.
These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em>
sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em>
element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:
em {
font-style: normal;
text-transform: uppercase;
}
Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong>
and <em>
had somewhat different meanings, <b>
and <i>
were purely presentational and had no semantic meaning whatsoever. Like <strong>
and <em>
respectively, they have similar presentational defaults but may be styled differently.
You use <strong>
and <em>
to indicate intense emphasis and normal emphasis respectively.
Or think of it this way: font-weight: bold
is closer to <b>
than <strong>
, and font-style: italic
is closer to <i>
than <em>
. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong>
and <em>
text in a more emphasized tone.
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
Replace the below line code:
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId==R.id.button1){
Intent i = new Intent(FromActivity.this, ToActivity.class);
startActivity(i);
}
}
}
Add the below lines in your manifest file:
<activity android:name="com.packagename.FromActivity"></activity>
<activity android:name="com.packagename.ToActivity"></activity>
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.
Add the following line to your php.ini
:
zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)
Note that when the path contains spaces you should wrap it in quotes:
zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"
Also note that you will have to use the zend_extension
directive instead of the "normal" extension
directive because it affects the actual Zend engine (i.e. the thing that runs PHP).
Currently there are four functions which you can use:
opcache_get_configuration()
:Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.
var_dump(opcache_get_configuration());
opcache_get_status()
:This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.
var_dump(opcache_get_status());
opcache_reset()
:Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.
opcache_reset();
opcache_invalidate()
:Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.
opcache_invalidate('/path/to/script/to/invalidate.php', true);
There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.
OpCacheGUI
Disclaimer I am the author of this project
Features:
Screenshots:
URL: https://github.com/PeeHaa/OpCacheGUI
opcache-status
Features:
Screenshot:
URL: https://github.com/rlerdorf/opcache-status
opcache-gui
Features:
Screenshot:
Since index positioning in Python is 0-based, there won't actually be an element in index
at the location corresponding to len(DF)
. You need that to be last_row = len(DF) - 1
:
In [49]: dfrm
Out[49]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
9 0.834706 0.002989 0.333436
[10 rows x 3 columns]
In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
[9 rows x 3 columns]
However, it's much simpler to just write DF[:-1]
.
Per the original docs:
Choose Anaconda if you:
Choose Miniconda if you:
I use Miniconda myself. Anaconda is bloated. Many of the packages are never used and could still be easily installed if and when needed.
Note that Conda is the package manager (e.g. conda list
displays all installed packages in the environment), whereas Anaconda and Miniconda are distributions. A software distribution is a collection of packages, pre-built and pre-configured, that can be installed and used on a system. A package manager is a tool that automates the process of installing, updating, and removing packages.
Anaconda is a full distribution of the central software in the PyData ecosystem, and includes Python itself along with the binaries for several hundred third-party open-source projects. Miniconda is essentially an installer for an empty conda environment, containing only Conda, its dependencies, and Python. Source.
Once Conda is installed, you can then install whatever package you need from scratch along with any desired version of Python.
2-4.4.0.1
is the version number for your Anaconda installation package. Strangely, it is not listed in their Old Package Lists.
In April 2016, the Anaconda versioning jumped from 2.5 to 4.0 in order to avoid confusion with Python versions 2 & 3. Version 4.0 included the Anaconda Navigator.
Release notes for subsequent versions can be found here.
This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.
for row in df.itertuples(index=False, name=None):
for k,v in enumerate(row):
print("column: {0}".format(df.columns.values[k]))
print("value: {0}".format(v)
If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words
.
Example:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests
):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
That solution will open up a new browser window without the normal features such as address bar and similar.
To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.
(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)
This shows the licence type and number of licences:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
it might help you..
Button download_image = (Button)bigimagedialog.findViewById(R.id.btn_downloadimage);
download_image.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
boolean success = (new File("/sdcard/dirname")).mkdir();
if (!success)
{
Log.w("directory not created", "directory not created");
}
try
{
URL url = new URL("YOUR_URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
String data1 = String.valueOf(String.format("/sdcard/dirname/%d.jpg",System.currentTimeMillis()));
FileOutputStream stream = new FileOutputStream(data1);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
Toast.makeText(getApplicationContext(), "Downloading Completed", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
Above solutions not helped me, but I resolve same issue by next way
private setHeaders(params) {
const accessToken = this.localStorageService.get('token');
const reqData = {
headers: {
Authorization: `Bearer ${accessToken}`
},
};
if(params) {
let reqParams = {};
Object.keys(params).map(k =>{
reqParams[k] = params[k];
});
reqData['params'] = reqParams;
}
return reqData;
}
and send request
this.http.get(this.getUrl(url), this.setHeaders(params))
Its work with NestJS backend, with other I don't know.
In (unusual) cases where you want to be able to dynamically change styles often -- e.g. a theme builder app -- adding <style> tags or calling CSSStyleSheet.insertRule() will result in a growing stylesheet, which can have performance and design debugging implications.
My approach only allows a single rule per selector/property combo, clearing any existing on setting any rule. The API is simple and flexible:
function addStyle(selector, rulename, value) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
var rule = stylesheet.insertRule(selector + ' { ' + rulename + ':' + value + ';}', cssRules.length);
}
function clearStyle(selector, rulename) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var i=0; i<cssRules.length; i++) {
var rule = cssRules[i];
if (rule.selectorText == selector && rule.style[0] == rulename) {
stylesheet.deleteRule(i);
break;
}
}
}
function addStyles(selector, rules) {
var stylesheet = getAppStylesheet();
var cssRules = stylesheet.cssRules || stylesheet.rules;
for (var prop in rules) {
addStyle(selector, prop, rules[prop]);
}
}
function getAppStylesheet() {
var stylesheet = document.getElementById('my-styles');
if (!stylesheet) {
stylesheet = $('<style id="my-styles">').appendTo('head')[0];
}
stylesheet = stylesheet.sheet;
return stylesheet;
}
Usage:
addStyles('body', {
'background-color': 'black',
color: 'green',
margin: 'auto'
});
clearStyle('body', 'background-color');
addStyle('body', 'color', '#333')
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.
When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")
I think it can't read the files due to User Account Control.
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
{}
represents an empty dictionary, not an array/list. For lists or arrays, you need []
.
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend
the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {}
or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update
method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
I think it has changed again.
For posting this works in Xcode 8.2.
NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)
One situation where it is quite useful to be able to handle the x-button click event is when you are using a Form that is an MDI container. The reason is that the closeing and closed events are raised first with children and lastly with the parent. So in one scenario a user clicks the x-button to close the application and the MDI parent asks for a confirmation to proceed. In case he decides to not close the application but carry on whatever he is doing the children will already have processed the closing event potentially lost information/work whatever. One solution is to intercept the WM_CLOSE message from the Windows message loop in your main application form (i.e. which closed, terminates the application) like so:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0010) // WM_CLOSE
{
// If we don't want to close this window
if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
}
base.WndProc(ref m);
}
I understand this post is old but if anybody is still searching and has not found a solution to the intellisense issue even after re-installing, applying the cumulative updates, or other methods, then I hope I may be of assistance.
I have Applied SQL 2008 R2 Service Pack 1 which you can download here
http://www.microsoft.com/download/en/details.aspx?id=26727
32 Bit: SQLServer2008R2SP1-KB2528583-x86-ENU.exe
64 Bit: SQLServer2008R2SP1-KB2528583-x64-ENU.exe
I have applied this SP1 and now my intellisense works again. I hope this helps! (:
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
This directly compares elements rather than just checking index numbers.
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"
Delete works faster =)
user system total real
gsub, s 0.180000 0.010000 0.190000 (0.193014)
gsub, s+ 0.200000 0.000000 0.200000 (0.196408)
gsub, space 0.220000 0.000000 0.220000 (0.222711)
gsub, join 0.200000 0.000000 0.200000 (0.193478)
delete 0.040000 0.000000 0.040000 (0.045157)
I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.
//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);
// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);
// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);
Here is a method:
public static void checkClass (Object obj) {
Class cls = obj.getClass();
System.out.println("The type of the object is: " + cls.getSimpleName());
}
@fthiella 's solution is very elegant.
If in future you want show more than user_id
you could use joins, and there in one line could be all data you need.
If you want to use AND
conditions, and the conditions are in multiple lines in your table, you can use JOINS
example:
SELECT `w_name`.`user_id`
FROM `wp_usermeta` as `w_name`
JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id`
AND `w_name`.`meta_key` = 'first_name'
AND `w_year`.`meta_key` = 'yearofpassing'
JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id
AND `w_city`.`meta_key` = 'u_city'
JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id`
AND `w_course`.`meta_key` = 'us_course'
WHERE
`w_name`.`meta_value` = '$us_name' AND
`w_year`.meta_value = '$us_yearselect' AND
`w_city`.`meta_value` = '$us_reg' AND
`w_course`.`meta_value` = '$us_course'
Other thing: Recommend to use prepared statements, because mysql_*
functions is not SQL injection save, and will be deprecated.
If you want to change your code the less as possible, you can use mysqli_
functions:
http://php.net/manual/en/book.mysqli.php
Recommendation:
Use indexes in this table. user_id
highly recommend to be and index, and recommend to be the meta_key
AND meta_value
too, for faster run of query.
The explain:
If you use AND
you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.
Tests: Table Data:
PRIMARY INDEX
int varchar(255) varchar(255)
/ \ |
+---------+---------------+-----------+
| user_id | meta_key | meta_value|
+---------+---------------+-----------+
| 1 | first_name | Kovge |
+---------+---------------+-----------+
| 1 | yearofpassing | 2012 |
+---------+---------------+-----------+
| 1 | u_city | GaPa |
+---------+---------------+-----------+
| 1 | us_course | PHP |
+---------+---------------+-----------+
The result of Query with $us_name='Kovge'
$us_yearselect='2012'
$us_reg='GaPa'
, $us_course='PHP'
:
+---------+
| user_id |
+---------+
| 1 |
+---------+
So it should works.
OPTION 1: if you want to make a common utility function then you can use this
export function getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
and use it by just importing it as
import {getCurrentDate} from './utils'
console.log(getCurrentDate())
OPTION 2: or define and use in a class directly
getCurrentDate(separator=''){
let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();
return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}
You can do this with php if the button opens a new page.
For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.
I exploded the url by '/' an got something like:
url[0] = pagename.php
<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>
<html>
<head>
<style>
.btn{
background:white;
}
.btn:hover,
.btn-on{
background:red;
}
</style>
</head>
<body>
<a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>
note: I didn't try this code. It might need adjustments.
Just use padding to wrap it like this:
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World!'),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Text('Hello World2!'),
)
]);
You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.
You can easily restart your MySql service. This kicks the error off.
You're using splice
in a wrong way.
The overloads are:
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)
Start means the index that you want to start, not the element you want to remove. And you should pass the second parameter deleteCount
as 1, which means: "I want to delete 1 element starting at the index {start}".
So you better go with:
deleteEvent: function(event) {
this.events.splice(this.events.indexOf(event), 1);
}
Also, you're using a parameter, so you access it directly, not with this.event
.
But in this way you will look up unnecessary for the indexOf
in every delete, for solving this you can define the index
variable at your v-for
, and then pass it instead of the event object.
That is:
v-for="(event, index) in events"
...
<button ... @click="deleteEvent(index)"
And:
deleteEvent: function(index) {
this.events.splice(index, 1);
}
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX
and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
I recommend using a autocomplete environment(pyscripter or scipy for example). If you lookup example code, make sure they use the same version of Python(if they don't make sure you change the code).
You can also hide spinner with following trick :
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity:0;
pointer-events:none;
}
As the answer is marked correct then it's a Windows Dos prompt script and this will work too:
find "string" status.txt >nul && call "my batch file.bat"
Yes there is, you can simply put <hr>
in your code where you want it, I already use it in one of my admin panel side bar.
The accept
attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input
. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.
Note: These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples.
h1 { font-size: 1em; margin:1em 0; }_x000D_
h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; }
_x000D_
<h1>Match all image files (image/*)</h1>_x000D_
<p><label>image/* <input type="file" accept="image/*"></label></p>_x000D_
_x000D_
<h1>Match all video files (video/*)</h1>_x000D_
<p><label>video/* <input type="file" accept="video/*"></label></p>_x000D_
_x000D_
<h1>Match all audio files (audio/*)</h1>_x000D_
<p><label>audio/* <input type="file" accept="audio/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and files with the extension ".someext"</h1>_x000D_
<p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and video files (video/*)</h1>_x000D_
<p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p>
_x000D_
The
accept
attribute may be specified to provide user agents with a hint of what file types will be accepted.If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:
The string
audio/*
- Indicates that sound files are accepted.
The string
video/*
- Indicates that video files are accepted.
The string
image/*
- Indicates that image files are accepted.
A valid MIME type with no parameters
- Indicates that files of the specified type are accepted.
A string whose first character is a U+002E FULL STOP character (.)
- Indicates that files with the specified file extension are accepted.
To get the form that the submit is inside why not just
this.form
Easiest & quickest path to the result.
Even though I'm sort of a broken clock with this one, Java XML API uses Factory a lot. I mean just look at this:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
String title = XPathFactory.newInstance().newXPath().evaluate("//title", doc);
...and so on and so forth.
Additionally various Buffers (StringBuffer, ByteBuffer, StringBuilder) use Builder.
The ascii values of the:
Up key - 224 72
Down key - 224 80
Left key - 224 75
Right key - 224 77
Each of these has two integer values for ascii value, because they are special keys, as opposed to the code for $, which is simply 36. These 2 byte special keys usually have the first digit as either 224, or 0. this can be found with the F# in windows, or the delete key.
EDIT : This may actually be unicode looking back, but they do work.
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
function sortAssocObject(list) {
var sortable = [];
for (var key in list) {
sortable.push([key, list[key]]);
}
// [["you",100],["me",75],["foo",116],["bar",15]]
sortable.sort(function(a, b) {
return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
});
// [["bar",15],["me",75],["you",100],["foo",116]]
var orderedList = {};
for (var idx in sortable) {
orderedList[sortable[idx][0]] = sortable[idx][1];
}
return orderedList;
}
sortAssocObject(list);
// {bar: 15, me: 75, you: 100, foo: 116}
Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.
<?php
mysqli_connect("localhost","root","","web_table");
mysql_select_db("web_table") or die(mysql_error());
for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use
$link = mysqli_connect("localhost","root","","web_table");
mysqli_select_db ($link , "web_table" ) or die.....
or for where i began
<?php $connection = mysqli_connect("localhost","root","","web_table");
global $connection; // global connection to databases - kill it once you're done
or just query with a $connection parameter as the other argument like above. Get rid of that third line.
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...
Here is how one could fairly easily use PyInstaller to solve the issue at hand:
pyinstaller oldlogs.py
From the tool's documentation:
PyInstaller analyzes myscript.py and:
- Writes myscript.spec in the same folder as the script.
- Creates a folder build in the same folder as the script if it does not exist.
- Writes some log files and working files in the build folder.
- Creates a folder dist in the same folder as the script if it does not exist.
- Writes the myscript executable folder in the dist folder.
In the dist folder you find the bundled app you distribute to your users.
If you like colors, try this:
for i in *; do echo; echo $'\e[33;1m'$i$'\e[0m'; cat $i; done | less -R
or:
tail -n +1 * | grep -e $ -e '==.*'
or: (with package 'multitail' installed)
multitail *
Try the following snippet, using a dictionary comprehension:
value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }
In the above code we find the difference of the keys and then rebuild a dict
taking the corresponding values.
If you're searching for character(s) in the start or at the end of the string, you can also use startsWith
and endsWith
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n'); // true
You need to add use Response;
facade in header at your file.
Only then you can successfully retrieve your data with
return Response::json($data);
EDIT: this answer isn't quite right at the moment, refer to my other answer to see what I was attempting to do here. I'm trying to fix it up, but if you can offer assistance do so in the comments, thanks!
Using padding-right
will mitigate the sudden appearance of a scrollbar
As you can see from the dots, the text makes it to the same point in the page before wrapping, regardless of whether or not a scrollbar is present.
This is because when a scrollbar is introduced the padding hides behind it, so the scrollbar doesn't push on the text!
The ViewExpiredException
will be thrown whenever the javax.faces.STATE_SAVING_METHOD
is set to server
(default) and the enduser sends a HTTP POST request on a view via <h:form>
with <h:commandLink>
, <h:commandButton>
or <f:ajax>
, while the associated view state isn't available in the session anymore.
The view state is identified as value of a hidden input field javax.faces.ViewState
of the <h:form>
. With the state saving method set to server
, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate()
in server, or due a server specific bug with session cookies as known in WildFly), then the serialized view state is not available anymore in the session and the enduser will get this exception. To understand the working of the session, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.
There is also a limit on the amount of views JSF will store in the session. When the limit is hit, then the least recently used view will be expired. See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews.
With the state saving method set to client
, the javax.faces.ViewState
hidden input field contains instead the whole serialized view state, so the enduser won't get a ViewExpiredException
when the session expires. It can however still happen on a cluster environment ("ERROR: MAC did not verify" is symptomatic) and/or when there's a implementation-specific timeout on the client side state configured and/or when server re-generates the AES key during restart, see also Getting ViewExpiredException in clustered environment while state saving method is set to client and user session is valid how to solve it.
Regardless of the solution, make sure you do not use enableRestoreView11Compatibility
. it does not at all restore the original view state. It basically recreates the view and all associated view scoped beans from scratch and hereby thus losing all of original data (state). As the application will behave in a confusing way ("Hey, where are my input values..??"), this is very bad for user experience. Better use stateless views or <o:enableRestorableView>
instead so you can manage it on a specific view only instead of on all views.
As to the why JSF needs to save view state, head to this answer: Why JSF saves the state of UI components on server?
In order to avoid ViewExpiredException
when e.g. navigating back after logout when the state saving is set to server
, only redirecting the POST request after logout is not sufficient. You also need to instruct the browser to not cache the dynamic JSF pages, otherwise the browser may show them from the cache instead of requesting a fresh one from the server when you send a GET request on it (e.g. by back button).
The javax.faces.ViewState
hidden field of the cached page may contain a view state ID value which is not valid anymore in the current session. If you're (ab)using POST (command links/buttons) instead of GET (regular links/buttons) for page-to-page navigation, and click such a command link/button on the cached page, then this will in turn fail with a ViewExpiredException
.
To fire a redirect after logout in JSF 2.0, either add <redirect />
to the <navigation-case>
in question (if any), or add ?faces-redirect=true
to the outcome
value.
<h:commandButton value="Logout" action="logout?faces-redirect=true" />
or
public String logout() {
// ...
return "index?faces-redirect=true";
}
To instruct the browser to not cache the dynamic JSF pages, create a Filter
which is mapped on the servlet name of the FacesServlet
and adds the needed response headers to disable the browser cache. E.g.
@WebFilter(servletNames={"Faces Servlet"}) // Must match <servlet-name> of your FacesServlet.
public class NoCacheFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
// ...
}
In order to avoid ViewExpiredException
when refreshing the current page when the state saving is set to server
, you not only need to make sure you are performing page-to-page navigation exclusively by GET (regular links/buttons), but you also need to make sure that you are exclusively using ajax to submit the forms. If you're submitting the form synchronously (non-ajax) anyway, then you'd best either make the view stateless (see later section), or to send a redirect after POST (see previous section).
Having a ViewExpiredException
on page refresh is in default configuration a very rare case. It can only happen when the limit on the amount of views JSF will store in the session is hit. So, it will only happen when you've manually set that limit way too low, or that you're continuously creating new views in the "background" (e.g. by a badly implemented ajax poll in the same page or by a badly implemented 404 error page on broken images of the same page). See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews for detail on that limit. Another cause is having duplicate JSF libraries in runtime classpath conflicting each other. The correct procedure to install JSF is outlined in our JSF wiki page.
When you want to handle an unavoidable ViewExpiredException
after a POST action on an arbitrary page which was already opened in some browser tab/window while you're logged out in another tab/window, then you'd like to specify an error-page
for that in web.xml
which goes to a "Your session is timed out" page. E.g.
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/WEB-INF/errorpages/expired.xhtml</location>
</error-page>
Use if necessary a meta refresh header in the error page in case you intend to actually redirect further to home or login page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Session expired</title>
<meta http-equiv="refresh" content="0;url=#{request.contextPath}/login.xhtml" />
</head>
<body>
<h1>Session expired</h1>
<h3>You will be redirected to login page</h3>
<p><a href="#{request.contextPath}/login.xhtml">Click here if redirect didn't work or when you're impatient</a>.</p>
</body>
</html>
(the 0
in content
represents the amount of seconds before redirect, 0
thus means "redirect immediately", you can use e.g. 3
to let the browser wait 3 seconds with the redirect)
Note that handling exceptions during ajax requests requires a special ExceptionHandler
. See also Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request. You can find a live example at OmniFaces FullAjaxExceptionHandler
showcase page (this also covers non-ajax requests).
Also note that your "general" error page should be mapped on <error-code>
of 500
instead of an <exception-type>
of e.g. java.lang.Exception
or java.lang.Throwable
, otherwise all exceptions wrapped in ServletException
such as ViewExpiredException
would still end up in the general error page. See also ViewExpiredException shown in java.lang.Throwable error-page in web.xml.
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/errorpages/general.xhtml</location>
</error-page>
A completely different alternative is to run JSF views in stateless mode. This way nothing of JSF state will be saved and the views will never expire, but just be rebuilt from scratch on every request. You can turn on stateless views by setting the transient
attribute of <f:view>
to true
:
<f:view transient="true">
</f:view>
This way the javax.faces.ViewState
hidden field will get a fixed value of "stateless"
in Mojarra (have not checked MyFaces at this point). Note that this feature was introduced in Mojarra 2.1.19 and 2.2.0 and is not available in older versions.
The consequence is that you cannot use view scoped beans anymore. They will now behave like request scoped beans. One of the disadvantages is that you have to track the state yourself by fiddling with hidden inputs and/or loose request parameters. Mainly those forms with input fields with rendered
, readonly
or disabled
attributes which are controlled by ajax events will be affected.
Note that the <f:view>
does not necessarily need to be unique throughout the view and/or reside in the master template only. It's also completely legit to redeclare and nest it in a template client. It basically "extends" the parent <f:view>
then. E.g. in master template:
<f:view contentType="text/html">
<ui:insert name="content" />
</f:view>
and in template client:
<ui:define name="content">
<f:view transient="true">
<h:form>...</h:form>
</f:view>
</f:view>
You can even wrap the <f:view>
in a <c:if>
to make it conditional. Note that it would apply on the entire view, not only on the nested contents, such as the <h:form>
in above example.
Unrelated to the concrete problem, using HTTP POST for pure page-to-page navigation isn't very user/SEO friendly. In JSF 2.0 you should really prefer <h:link>
or <h:button>
over the <h:commandXxx>
ones for plain vanilla page-to-page navigation.
So instead of e.g.
<h:form id="menu">
<h:commandLink value="Foo" action="foo?faces-redirect=true" />
<h:commandLink value="Bar" action="bar?faces-redirect=true" />
<h:commandLink value="Baz" action="baz?faces-redirect=true" />
</h:form>
better do
<h:link value="Foo" outcome="foo" />
<h:link value="Bar" outcome="bar" />
<h:link value="Baz" outcome="baz" />
I'll go 1 step further to make sure the property is indeed a function
function js_to_as( str ){
if (me && me.onChange && typeof me.onChange === 'function') {
me.onChange(str);
}
}
Now docker-compose
supports variable substitution.
Compose uses the variable values from the shell environment in which docker-compose
is run. For example, suppose the shell contains POSTGRES_VERSION=9.3
and you supply this configuration in your docker-compose.yml
file:
db:
image: "postgres:${POSTGRES_VERSION}"
When you run docker-compose up
with this configuration, Compose looks for the POSTGRES_VERSION
environment variable in the shell and substitutes its value in. For this example, Compose resolves the image
to postgres:9.3
before running the configuration.
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
You can also use a Bridged Network (or "Bridge Adapter", in newer versions) in network settings. This will put your VM in a VLAN with your machine. So you can just ssh into the VM like this.
ssh user@IP_OF_VM
Chances are, you'll have cut
as well. If so:
[me@home]$ echo "pid: 1234" | cut -d" " -f2
1234
This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)
How about
<button onclick="window.open('http://www.google.com','name','width=200,height=200');">Open</button>
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
For docker on macOS, you can use docker-time-sync-agent. It works for me.
The best solution I've found is to leave Eclipse in normal bright mode, and use an OS level screen inverter.
On OS X you can do Command + Option + Ctrl + 8, inverts the whole screen.
On Linux with Compiz, it's even better, you can do Windows + N to darken windows selectively (or Windows + M to do the whole screen).
On Windows, the only decent solution I've found is powerstrip, but it's only free for one year... then it's like $30 or something...
Then you can invert the screen, adjust the syntax-level colours to your liking, and you're off to the races, with cool shades on.
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload
.
Here, Something about abstract class...
Real time example--
If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.
abstract class WagonX
{
public abstract void model();
public abstract void color();
public static void baseEngine()
{
// your logic here
}
public static void size()
{
// logic here
}
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}
I've also seen this error in solutions where I have multiple projects (usually netTiers projects where I've updated one or more of the sub-projects to target the 4.0 framework). It can be problematic to remove. Oftentimes it can be resolved, however, by first fixing all other errors in sub-projects (eg, any missing references), individually rebuilding those sub-projects, then removing/adding back any references to those sub-projects in Visual Studio. Personally, I've had little luck resolving this error by cleaning the solution alone.