function insertHtml(id, html)
{
var ele = document.getElementById(id);
ele.innerHTML = html;
var codes = ele.getElementsByTagName("script");
for(var i=0;i<codes.length;i++)
{
eval(codes[i].text);
}
}
It works in Chrome in my project
It greatly reduces your level of confidence about security.
ast.literal_eval()
only considers a small subset of Python's syntax to be valid:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and
None
.
Passing __import__('os').system('rm -rf /a-path-you-really-care-about')
into ast.literal_eval()
will raise an error, but eval()
will happily delete your files.
Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval()
. It safely does what you want and nothing more.
exec is for statement and does not return anything. eval is for expression and returns value of expression.
expression means "something" while statement means "do something".
I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.
As there are many answers, I'm adding my implementation on top of eval()
method with some additional features like support for factorial, evaluating complex expressions etc.
package evaluation;
import java.math.BigInteger;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class EvalPlus {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This Evaluation is based on BODMAS rule\n");
evaluate();
}
private static void evaluate() {
StringBuilder finalStr = new StringBuilder();
System.out.println("Enter an expression to evaluate:");
String expr = scanner.nextLine();
if(isProperExpression(expr)) {
expr = replaceBefore(expr);
char[] temp = expr.toCharArray();
String operators = "(+-*/%)";
for(int i = 0; i < temp.length; i++) {
if((i == 0 && temp[i] != '*') || (i == temp.length-1 && temp[i] != '*' && temp[i] != '!')) {
finalStr.append(temp[i]);
} else if((i > 0 && i < temp.length -1) || (i==temp.length-1 && temp[i] == '!')) {
if(temp[i] == '!') {
StringBuilder str = new StringBuilder();
for(int k = i-1; k >= 0; k--) {
if(Character.isDigit(temp[k])) {
str.insert(0, temp[k] );
} else {
break;
}
}
Long prev = Long.valueOf(str.toString());
BigInteger val = new BigInteger("1");
for(Long j = prev; j > 1; j--) {
val = val.multiply(BigInteger.valueOf(j));
}
finalStr.setLength(finalStr.length() - str.length());
finalStr.append("(" + val + ")");
if(temp.length > i+1) {
char next = temp[i+1];
if(operators.indexOf(next) == -1) {
finalStr.append("*");
}
}
} else {
finalStr.append(temp[i]);
}
}
}
expr = finalStr.toString();
if(expr != null && !expr.isEmpty()) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
System.out.println("Result: " + engine.eval(expr));
evaluate();
} catch (ScriptException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("Please give an expression");
evaluate();
}
} else {
System.out.println("Not a valid expression");
evaluate();
}
}
private static String replaceBefore(String expr) {
expr = expr.replace("(", "*(");
expr = expr.replace("+*", "+").replace("-*", "-").replace("**", "*").replace("/*", "/").replace("%*", "%");
return expr;
}
private static boolean isProperExpression(String expr) {
expr = expr.replaceAll("[^()]", "");
char[] arr = expr.toCharArray();
Stack<Character> stack = new Stack<Character>();
int i =0;
while(i < arr.length) {
try {
if(arr[i] == '(') {
stack.push(arr[i]);
} else {
stack.pop();
}
} catch (EmptyStackException e) {
stack.push(arr[i]);
}
i++;
}
return stack.isEmpty();
}
}
Please find the updated gist anytime here. Also comment if any issues are there. Thanks.
I like the "evaluating your expression one additional time before execution" answer, and would like to clarify with another example.
var="\"par1 par2\""
echo $var # prints nicely "par1 par2"
function cntpars() {
echo " > Count: $#"
echo " > Pars : $*"
echo " > par1 : $1"
echo " > par2 : $2"
if [[ $# = 1 && $1 = "par1 par2" ]]; then
echo " > PASS"
else
echo " > FAIL"
return 1
fi
}
# Option 1: Will Pass
echo "eval \"cntpars \$var\""
eval "cntpars $var"
# Option 2: Will Fail, with curious results
echo "cntpars \$var"
cntpars $var
The Curious results in Option 2 are that we would have passed 2 parameters as follows:
"value
content"
How is that for counter intuitive? The additional eval
will fix that.
Adapted from https://stackoverflow.com/a/40646371/744133
It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
I agree that this var formattedString = string.replace(/'/g, "\\'");
works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \
and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \
was the work around.
This works too, with the semi-colon.
NAME=sam; echo $NAME
Put the classname into a variable first:
$classname=$var.'Class';
$bar=new $classname("xyz");
This is often the sort of thing you'll see wrapped up in a Factory pattern.
See Namespaces and dynamic language features for further details.
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
If you want to toggle text with a toggle button.
HTMLfile which is using bootstrap:
<input class="btn" (click)="muteStream()" type="button"
[ngClass]="status ? 'btn-success' : 'btn-danger'"
[value]="status ? 'unmute' : 'mute'"/>
TS file:
muteStream() {
this.status = !this.status;
}
simple util function to calculate distance between two geopoints:
public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {
double l1 = toRadians(lat1);
double l2 = toRadians(lat2);
double g1 = toRadians(lng1);
double g2 = toRadians(lng2);
double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
if(dist < 0) {
dist = dist + Math.PI;
}
return Math.round(dist * 6378100);
}
I wasn't able to copy to my clipboard's system because I had this in my ~/.vimrc file:
if has('mouse')
set mouse=a
endif
But if you add this line next, it will allow you to simply Ctrl+c to get whatever you have selected into your clipboard.
vmap <C-c> "+y
Original discussion and more details: Copy text out of vim with set mouse=a enabled
This is slightly adapted version of Sean's which was preventing back button
// this function makes anchor tags work properly on an iphone
$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
// For iOS Apps
$("a").on("click", function(e){
var new_location = $(this).attr("href");
if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
e.preventDefault();
window.location = new_location;
}
});
}
});
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
Using an escaped string (a.k.a. escaped value):
width: ~"calc(100% - 200px)";
Also, in case you need to mix Less math with escaped strings:
width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");
Compiles to:
width: calc(100% - 15rem + 15px + 2em);
This works as Less concatenates values (the escaped strings and math result) with a space by default.
Try <input type="number" step="any" />
It won't have validation problems and the arrows will have step of "1"
Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.
The following range control only accepts values in the range 0..1, and allows 256 steps in that range:
<input name=opacity type=range min=0 max=1 step=0.00392156863>
The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):
<input name=favtime type=time step=any>
Normally, time controls are limited to an accuracy of one minute.
http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step
For what it's worth my issue was that the files themselves were in the wrong encoding. Using iconv worked for me
iconv -f ISO-8859-15 -t UTF-8 messages_nl.properties > messages_nl.properties.new
Here is an alternative approach that I used to detect the text blocks:
Below is the code written in python with pyopencv, it should easy to port to C++.
import cv2
image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours
# for each contour found, draw a rectangle around it on original image
for contour in contours:
# get rectangle bounding contour
[x,y,w,h] = cv2.boundingRect(contour)
# discard areas that are too large
if h>300 and w>300:
continue
# discard areas that are too small
if h<40 or w<40:
continue
# draw rectangle around contour on original image
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
# write original image with added contours to disk
cv2.imwrite("contoured.jpg", image)
The original image is the first image in your post.
After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:
Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:
You can see the text block on the left is detected as a separate block, delimited from its surroundings.
Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:
The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.
For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY
). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.
Finding other object types:
For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):
Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.
If you want the latest Beta, it will not be in the AppStore. Instead you have to login to https://developer.apple.com and download from there.
This is probably unpopular way. But here how I do it:
object1 = // object to copy
YourClass *object2 = [[YourClass alloc] init];
object2.property1 = object1.property1;
object2.property2 = object1.property2;
..
etc.
Quite simple and straight forward. :P
I had some problems with lists of float values. I ended up using a code snippet from the python3 statistics.median and is working perfect with float values without imports. source
def calculateMedian(list):
data = sorted(list)
n = len(data)
if n == 0:
return None
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2
The code below will produce this plot:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]
# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]
# A dataframe
df = pd.DataFrame(data)
def CorrMtx(df, dropDuplicates = True):
# Your dataset is already a correlation matrix.
# If you have a dateset where you need to include the calculation
# of a correlation matrix, just uncomment the line below:
# df = df.corr()
# Exclude duplicate correlations by masking uper right values
if dropDuplicates:
mask = np.zeros_like(df, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set background color / chart style
sns.set_style(style = 'white')
# Set up matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Add diverging colormap from red to blue
cmap = sns.diverging_palette(250, 10, as_cmap=True)
# Draw correlation plot with or without duplicates
if dropDuplicates:
sns.heatmap(df, mask=mask, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
else:
sns.heatmap(df, cmap=cmap,
square=True,
linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
CorrMtx(df, dropDuplicates = False)
I put this together after it was announced that the outstanding seaborn corrplot
was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap
. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of
0.95173379, try changing to -0.95173379 and you'll get this:
A little twist on the union query:
DECLARE @Foo TABLE (ID INT, Col1 INT, Col2 INT, Col3 INT)
INSERT @Foo (ID, Col1, Col2, Col3)
VALUES
(1, 3, 34, 76),
(2, 32, 976, 24),
(3, 7, 235, 3),
(4, 245, 1, 792)
SELECT
ID,
Col1,
Col2,
Col3,
(
SELECT MIN(T.Col)
FROM
(
SELECT Foo.Col1 AS Col UNION ALL
SELECT Foo.Col2 AS Col UNION ALL
SELECT Foo.Col3 AS Col
) AS T
) AS TheMin
FROM
@Foo AS Foo
Check for the SendCommand tool.
You can use it as follows:
perl sendcommand.pl -i login.txt -t cisco -c "show ip route"
Here's the whole code snippet needed:
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
I use a similar technique to lazyload images, but can't help but notice that Javascript doesn't access the browser cache on first loading.
My example:
I have a rotating banner on my homepage with 4 images the slider wait 2 seconds, than the javascript loads the next image, waits 2 seconds, etc.
These images have unique urls that change whenever I modify them, so they get caching headers that will cache in the browser for a year.
max-age: 31536000, public
Now when I open Chrome Devtools and make sure de 'Disable cache' option is not active and load the page for the first time (after clearing the cache) all images get fetch and have a 200 status. After a full cycle of all images in the banner the network requests stop and the cached images are used.
Now when I do a regular refresh or go to a subpage and click back, the images that are in the cache seems to be ignored. I would expect to see a grey message "from disk cache" in the Network tab of Chrome devtools. In instead I see the requests pass by every two seconds with a Green status circle instead of gray, I see data being transferred, so it I get the impression the cache is not accessed at all from javascript. It simply fetches the image each time the page gets loaded.
So each request to the homepage triggers 4 requests regardless of the caching policy of the image.
Considering the above together and the new http2 standard most webservers and browsers now support, I think it's better to stop using lazyloading since http2 will load all images nearly simultaneously.
If this is a bug in Chrome Devtools it really surprises my nobody noticed this yet. ;)
If this is true, using lazyloading only increases bandwith usage.
Please correct me if I'm wrong. :)
Yes, you can use numpy
for that.
import numpy as np
a = arange(3,dtype=float)
a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf
a # is now [nan,inf,-inf]
np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True
No, there is no chance to do that. You just learned how important a backup can be.
This Code is for New Java Learners:
private String textDataFromFile;
public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {
BufferedReader bufferReader = new BufferedReader (new InputStreamReader(myInputStream));
StringBuilder stringBuilder = new StringBuilder();
String eachStringLine;
while((eachStringLine=bufferReader.readLine()) != null){
stringBuilder.append(eachStringLine).append("\n");
}
textDataFromFile = stringBuilder.toString();
return textDataFromFile;
}
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config
is not a valid variable name. $.FullName
should be $_.FullName
$
should be $_.Name
Actually, guys, there is a way. I struggled mightily to figure this out for [LINK REMOVED] (try it on an iPhone or iPad).
Basically, Safari on touchscreen devices is stingy when it comes to focus()
ing textboxes. Even some desktop browsers do better if you do click().focus()
. But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions:
1) The user clicked somewhere and focus()
was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false})
option in jQuery.
2) Furthermore -- and this one kept me busy for a while -- focus()
still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart
event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend
event of the Go button, and this worked like a charm!
When you put #1 and #2 together, you get a magical result that will set your login forms apart from all the crappy web login forms, by placing the focus in your password fields, and make them feel more native. Enjoy! :)
As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
var map = arr.reduce(function(prev, cur) {_x000D_
prev[cur] = (prev[cur] || 0) + 1;_x000D_
return prev;_x000D_
}, {});_x000D_
_x000D_
// map is an associative array mapping the elements to their frequency:_x000D_
document.write(JSON.stringify(map));_x000D_
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
_x000D_
Try this to read a file:
BufferedReader reader = null;
try {
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName);
anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).
// If the DGV does not have Focus prior to a toolbar button Click,
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.
private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;
public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
// This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
m_SelectCellFocus_DataPropertyName = sDataPropertyName;
timer_CellFocus = new System.Timers.Timer(10);
timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
timer_CellFocus.Start();
}
void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
timer_CellFocus.Stop();
timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
timer_CellFocus.Dispose();
// We have to Invoke the method to avoid raising a threading error
this.Invoke((MethodInvoker)delegate
{
Select_Cell(m_SelectCellFocus_DataPropertyName);
});
}
private void Select_Cell(string sDataPropertyName)
{
/// When the Edit Mode is Enabled, set the initial cell to the Description
foreach (DataGridViewCell dgvc in this.SelectedCells)
{
// Clear previously selected cells
dgvc.Selected = false;
}
foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
{
// Select the Cell by its DataPropertyName
if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
{
this.CurrentCell = dgvc;
dgvc.Selected = true;
this.Focus();
return;
}
}
}
I found a caveat that no one so far has mentioned. I don't know if it will come up often in practical situations, but here it is for the sake of completeness.
Usually, calculating a number modulo infinity returns itself as a float, but a fraction modulo infinity returns nan
(not a number). Here is an example:
>>> from fractions import Fraction
>>> from math import inf
>>> 3 % inf
3.0
>>> 3.5 % inf
3.5
>>> Fraction('1/3') % inf
nan
I filed an issue on the Python bug tracker. It can be seen at https://bugs.python.org/issue32968.
Update: this will be fixed in Python 3.8.
You can use readelf
to explore the ELF headers. readelf -d
will list the direct dependencies as NEEDED
sections.
$ readelf -d elfbin
Dynamic section at offset 0xe30 contains 22 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libssl.so.1.0.0]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000000c (INIT) 0x400520
0x000000000000000d (FINI) 0x400758
...
I resolved it like this:
<% @user.errors.each do |attr, msg| %>
<li>
<%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
</li>
<% end %>
This way you are using the locales for the error messages.
Try in your webpack.mix.js to add the '*'
.copy('node_modules/font-awesome/fonts/*', 'public/fonts')
<?php
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>
I am developing an app to version 2.2, API version would in the 8th ... had the same error and the error told me it was to google maps API, all we did was change my ADV for my project API 2.2 and also for the API.
This worked for me and found the library API needed.
Here is my solution
[^0-9A-Z,\n]
This will remove all the digits, commas and new lines but select the middle space such as data set of
I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities
are used like setting your config with key-value pair.
Below is an example related to Appium
used for Automating Mobile platforms like Android
and IOS
.
So we generally set DesiredCapabilities
for conveying our WebDriver
for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.
So we set our DesiredCapabilities as:
// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();
// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");
// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");
// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");
// Set android appPackage desired capability.
//You need to check for your appPackage Name for your app, you can use this app for that APK INFO
// Set your application's appPackage if you are using any other app.
capabilities.setCapability("appPackage", "com.android.appPackageName");
// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");
This DesiredCapabilities
are very specific to Appium
on Android
Platform.
For more you can refer to the official site of Selenium desiredCapabilities class
You should put this line in your application context:
<context:component-scan base-package="com.cinebot.service" />
Read more about Automatically detecting classes and registering bean definitions in documentation.
This is a simpler one
$('#some_select_box').find('option:selected').remove().end();
^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.
So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"
Here's a quick reference: http://www.regular-expressions.info/reference.html
Never mind, figured it out:
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
Which I found by:
show all
And looking for some option that seemed relevant.
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular.
So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.
app.service("Logger", Logger); // Injects a global object
When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.
app.factory("Customerfactory", CreateCustomer);
Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.
Factory should be used When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. Here is a detailed explanation of this paragraph
Service should be used When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
That's shorter.
function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}
A KISS offering:
def remove_if_exists(filename):
if os.path.exists(filename):
os.remove(filename)
And then:
remove_if_exists("my.file")
do you mean empty or null, two different things,
if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null
The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here
string s = "hello";
char c = s[1];
// now c == 'e'
See also Substring
, to return more than one character.
Yes, your query strings will be encrypted.
The reason behind is that query strings are part of the HTTP protocol which is an application layer protocol, while the security (SSL/TLS) part comes from the transport layer. The SSL connection is established first and then the query parameters (which belong to the HTTP protocol) are sent to the server.
When establishing an SSL connection, your client will perform the following steps in order. Suppose you're trying to log in to a site named example.com and want to send your credentials using query parameters. Your complete URL may look like the following:
https://example.com/login?username=alice&password=12345)
example.com
to an IP address (124.21.12.31)
using a DNS request. When querying that information, only domain specific information is used, i.e., only example.com
will be used.124.21.12.31
and will attempt to connect to port 443 (SSL service port not the default HTTP port 80).example.com
will send its certificates to your client.Therefore, you won't expose sensitive data. However, sending your credentials over an HTTPS session using this method is not the best way. You should go for a different approach.
Use bases if you just want to get the parents, use __mro__
(as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).
Bases (and first getting the class for an existing object):
>>> some_object = "some_text"
>>> some_object.__class__.__bases__
(object,)
For mro in recent Python versions:
>>> some_object = "some_text"
>>> some_object.__class__.__mro__
(str, object)
Obviously, when you already have a class definition, you can just call __mro__
on that directly:
>>> class A(): pass
>>> A.__mro__
(__main__.A, object)
For anyone coming here from search results and are targeting Android 10: Android 10 (API 29) changes some permissions related to storage.
I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory()
(which is deprecated with API 29) with context.getExternalFilesDir(null)
.
Note that context.getExternalFilesDir(type)
can return null if the storage location isn't available, so be sure to check that whenever you're checking if you have external permissions.
Read more here.
With the release of C# 6, you can now do something like this for private properties.
public constructor()
{
myProp = "some value";
}
public string myProp { get; }
For the few people asking for a generic method, this should help you (5 years later :p).
For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the
for (Method method: clazz.getMethods())
to
for (Field field: clazz.getFields())
And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).
public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
// Only continue if the method name is not empty.
if ((methodName != null) && (methodName.trim().length() > 0))
{
RequestMapping tmpRequestMapping;
String[] tmpValues;
// Loop over all methods in the class.
for (Method method: clazz.getMethods())
{
// If the current method name matches the expected method name, then keep going.
if (methodName.equalsIgnoreCase(method.getName()))
{
// Try to extract the RequestMapping annotation from the current method.
tmpRequestMapping = method.getAnnotation(RequestMapping.class);
// Only continue if the current method has the RequestMapping annotation.
if (tmpRequestMapping != null)
{
// Extract the values from the RequestMapping annotation.
tmpValues = tmpRequestMapping.value();
// Only continue if there are values.
if ((tmpValues != null) && (tmpValues.length > 0))
{
// Return the 1st value.
return tmpValues[0];
}
}
}
}
}
// Since no value was returned, log it and return an empty string.
logger.error("Failed to find RequestMapping annotation value for method: " + methodName);
return "";
}
I ran into issues when replacing a small placeholder with a large string of code.
I was doing:
var replaced = original.replace('PLACEHOLDER', largeStringVar);
I figured out the problem was JavaScript's special replacement patterns, described here. Since the code I was using as the replacing string had some $
in it, it was messing up the output.
My solution was to use the function replacement option, which DOES NOT do any special replacement:
var replaced = original.replace('PLACEHOLDER', function() {
return largeStringVar;
});
This drove me absolutely nuts for a day and a half but I found a solution if all other solutions have been tried unsuccessfully.
This is for macOS.
At that point I immediately stopped getting 403 errors and everything started working as expected. Weird thing is i didn't even have to restart apache it just worked, i guess it restarted itself when i went to my localhost, I honestly don't know but I guess the problem is Apache not actually restarting when using apachectl restart, or stop or start. Hope this helps someone.
When you start your script, a new process is created that only inherits your environment. When it ends, it ends. Your current environment stays as it is.
Instead, you can start your script like this:
. myscript.sh
The .
will evaluate the script in the current environment, so it might be altered
A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.
You denote that fact by appending the "= 0" to the declaration, like this:
class AbstractBase
{
virtual void PureVirtualFunction() = 0;
}
Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:
class Derived : public AbstractBase
{
virtual void PureVirtualFunction() override { }
}
By adding the override
keyword, the compiler will ensure that there is a base class virtual function with the same signature.
Apparently, using Hibernate5Module, the @Transient will not be serialize if using ObjectMapper. Removing will make it work.
import javax.persistence.Transient;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TransientFieldTest {
@Test
public void Print_Json() throws JsonProcessingException {
ObjectMapper objectEntityMapper = new ObjectMapper();
//objectEntityMapper.registerModule(new Hibernate5Module());
objectEntityMapper.setSerializationInclusion(Include.NON_NULL);
log.info("object: {}", objectEntityMapper.writeValueAsString( //
SampleTransient.builder()
.id("id")
.transientField("transientField")
.build()));
}
@Getter
@Setter
@Builder
private static class SampleTransient {
private String id;
@Transient
private String transientField;
private String nullField;
}
}
var div = document.createElement('div');
document.body.appendChild(div);
div.style.left = '32px';
div.style.top = '-16px';
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
div.parentNode.removeChild(div);
div = document.getElementById('test');
array = document.getElementsByTagName('div');
array = document.getElementsByClassName('ui-modal');
div = document.querySelector('div #test .ui-modal');
array = document.querySelectorAll('div');
This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.
function uploadfile(ctrl) {
var validate = validateimg(ctrl);
if (validate) {
if (window.FormData !== undefined) {
ShowLoading();
var fileUpload = $(ctrl).get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
fileData.append('username', 'Wishes');
$.ajax({
url: 'UploadWishesFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function(result) {
var id = $(ctrl).attr('id');
$('#' + id.replace('txt', 'hdn')).val(result);
$('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();
HideLoading();
},
error: function(err) {
alert(err.statusText);
HideLoading();
}
});
} else {
alert("FormData is not supported.");
}
}
You can always do it programmatically as suggested by the other answers over here. But for development purpose, I find this Plugin
very helpful as it speeds up my development significantly.
PLUGIN: ADB Idea
It provides you with features to Clear App Data and Revoke Permission from your Android Studio itself, just with click of a button.
SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').
Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.
If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:
let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';
If ther's a where
statement in your query and/or trying to insert
a value and/or an update
of value which is string use single quote(') for these values like:
let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";
//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error
let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';
//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.
If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:
let query = 'select is, name from accounts where name = \'John\'';
Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:
let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith
//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";
//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';
If need further clearance do follow quotes in JavaScript
Try this, using the prototype.js
library:
string.escapeHTML();
Without any configuration, you can simply issue the following command (modifying myusername
and mydomain
with your own information):
cntlm -u myusername -d mydomain -H
or
cntlm -u myusername@mydomain -H
It will ask you the password of myusername
and will give you the following output:
PassLM 1AD35398BE6565DDB5C4EF70C0593492
PassNT 77B9081511704EE852F94227CF48A793
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC # Only for user 'myusername', domain 'mydomain'
Then create the file cntlm.ini
(or cntlm.conf
on Linux using default path) with the following content (replacing your myusername
, mydomain
and A8FC9092D566461E6BEA971931EF1AEC
with your information and the result of the previous command):
Username myusername
Domain mydomain
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:5865
Gateway yes
SOCKS5Proxy 5866
Auth NTLMv2
PassNTLMv2 A8FC9092D566461E6BEA971931EF1AEC
Then you will have a local open proxy on local port 5865
and another one understanding SOCKS5 protocol at local port 5866
.
ConfirmDialog('Are you sure');_x000D_
_x000D_
function ConfirmDialog(message) {_x000D_
$('<div></div>').appendTo('body')_x000D_
.html('<div><h6>' + message + '?</h6></div>')_x000D_
.dialog({_x000D_
modal: true,_x000D_
title: 'Delete message',_x000D_
zIndex: 10000,_x000D_
autoOpen: true,_x000D_
width: 'auto',_x000D_
resizable: false,_x000D_
buttons: {_x000D_
Yes: function() {_x000D_
// $(obj).removeAttr('onclick'); _x000D_
// $(obj).parents('.Parent').remove();_x000D_
_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
},_x000D_
No: function() {_x000D_
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');_x000D_
_x000D_
$(this).dialog("close");_x000D_
}_x000D_
},_x000D_
close: function(event, ui) {_x000D_
$(this).remove();_x000D_
}_x000D_
});_x000D_
};
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
_x000D_
There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.
If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.
Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.
Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.
I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.
public class DateTimeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.RequestType == "GET")
{
foreach (var parameter in filterContext.ActionParameters)
{
var properties = parameter.Value.GetType().GetProperties();
foreach (var property in properties)
{
Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
{
DateTime dateTime;
if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
property.SetValue(parameter.Value, dateTime,null);
}
}
}
}
}
}
Your understanding is correct. However, if we walk through:
(.*)
will swallow the whole string;(\\d+)
is satistifed (which is why 0
is captured, and not 3000
);(.*)
will then capture the rest.I am not sure what the original intent of the author was, however.
If you are doing it before the setContentView()
method call, then the values will be null.
This will result in null:
super.onCreate(savedInstanceState);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
setContentView(R.layout.main_contacts);
while this will work fine:
super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
It's generally only an issue if you're passing eval user input.
I answered this already, but some reason the answer was converted to a comment. Nevertheless, this is the most efficient solution:
Not being able to include (and propagate) NaNs in groups is quite aggravating. Citing R is not convincing, as this behavior is not consistent with a lot of other things. Anyway, the dummy hack is also pretty bad. However, the size (includes NaNs) and the count (ignores NaNs) of a group will differ if there are NaNs.
dfgrouped = df.groupby(['b']).a.agg(['sum','size','count'])
dfgrouped['sum'][dfgrouped['size']!=dfgrouped['count']] = None
When these differ, you can set the value back to None for the result of the aggregation function for that group.
I know this a very much late reply but I saw this query recently And found a working scenario,
OnClick of Submit use the below code:
$('#Submit').click(function ()
{ $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
return false });
To Stop the Gif use the below code:
$('#Submit').ajaxStop();
Solution for UBUNTU Worked for me:
Installed tesseract in ubuntu by following below link
https://medium.com/quantrium-tech/installing-tesseract-4-on-ubuntu-18-04-b6fcd0cbd78f
Later added traindata language to tessdata by following below link
Project Properties \ Output file -> Select Class Library :)
If you really want to, you can check it manually by using null
:
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
if(param3 == null) {
param3 = false;
}
}
However i heavily recommend using something else, like overloading or a static factory. Maybe you can get away with this, but it can lead to unexcspected behavior. For example you could have an error in your code, so that your boolean never gets a value. In this case you would not get a NullPointerException
. Instead it will look like it was set to false, which can be very confusing to debug.
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
This worked for me in my template:
{{ request.scheme }}://{{ request.META.HTTP_HOST }}{% url 'equipos:marca_filter' %}
I needed the full url to pass it to a js fetch function. I hope this help you.
You can create swap space using the following steps
Here we are creating swap at /home/
dd if=/dev/zero of=/home/swapfile1 bs=1024 count=8388608
Here count is kilobyte count of swap space
mkswap /home/swapfile1
vi /etc/fstab
make entry :
/home/swapfile1 swap swap defaults 0 0
run:
swapon -a
public static void main(String[] args) {
List<String> ls=new ArrayList<String>();
ls.add("1");
ls.add("2");
ls.add("3");
ls.add("4");
//Then you can use "foreache" loop to iterate.
for(String item:ls){
System.out.println(item);
}
}
tomcat.sh
helps you know this easily.
tomcat.sh usage doc says:
no argument: display the process-id of the tomcat, if it's running, otherwise do nothing
So, run command on your command prompt and check for pid:
$ tomcat.sh
In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
Between the deprecation of mutation events and the emergence of MutationObserver
, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.
To quote the blog post:
Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for.
I used a relatively benign and little used css property, clipI used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.
I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....
So here's my answer and can be run out of the box.
<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {
$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})
$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end = $('#enddate').datepicker('getDate');
if (start<end) {
var days = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>
a Fiddle can be seen here DEMO
To actually do it in HTML with inline CSS (not with an external CSS style sheet)
<input type="text" style="font-size: 44pt">
A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html>
or <body>
tag, and such is appropriate there.
i have same issue and resolved by
data: "Id1=" + id1 + "&Id2=" + id2
private void btnEnter_Click(object sender, EventArgs e)
{
maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.ValidatingType = typeof(System.DateTime);
//if (!IsValidDOB(maskedTextBox1.Text))
if (!ValidateBirthday(maskedTextBox1.Text))
MessageBox.Show(" Not Valid");
else
MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{
DateTime temp;
if (DateTime.TryParse(dob, out temp))
return (true);
else
return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true &&
Temp.Year > 1900 &&
// Temp.Hour == 0 && Temp.Minute == 0 &&
//Temp.Second == 0 && Temp.Millisecond == 0 &&
Temp > DateTime.MinValue)
return (true);
else
return (false);
}
Swift
Following UIView Extension will remove all Edge constraints of a view:
extension UIView {
func removeAllConstraints() {
if let _superview = self.superview {
self.removeFromSuperview()
_superview.addSubview(self)
}
}
}
Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some static datasource), the getter-only property is generally the preferred pattern.
On Servlet 3.0 or newer you could just specify
<web-app ...>
<error-page>
<location>/general-error.html</location>
</error-page>
</web-app>
But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.
<error-page>
<!-- Missing login -->
<error-code>401</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Forbidden directory listing -->
<error-code>403</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Missing resource -->
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
<error-page>
<!-- Uncaught exception -->
<error-code>500</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Unsupported servlet method -->
<error-code>503</error-code>
<location>/general-error.html</location>
</error-page>
That should cover the most common ones.
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Pass CultureInfo.InvariantCulture as the second parameter of DateTime, it will return the string as what you want, even a very special format:
DateTime.Now.ToString("dd|MM|yyyy", CultureInfo.InvariantCulture)
will return: 28|02|2014
The following strings are all of use when you want to retrieve manufacturer, name of the device, and/or the model:
String manufacturer = Build.MANUFACTURER;
String brand = Build.BRAND;
String product = Build.PRODUCT;
String model = Build.MODEL;
If you use an operating system that uses copy-on-write fork()
semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).
The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy
or array
), place that in shared memory, wrap it with multiprocessing.Array
, and pass that to your functions. This answer shows how to do that.
If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing
provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager
proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).
The Manager
approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.
There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing
is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.
I had the same issue and I fixed it this way:
mywork
.myWork
. Let us call the class HelloWorld
.Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.
Xauthority becomes an issue with newer systems. I can either discard any protection with xhost + before running my docker containers, or I can pass in a well prepared Xauthority file. Typical Xauthority files are hostname specific. With docker, each container can have a different host name (set with docker run -h), but even setting the hostname of the container identical to the host system did not help in my case. xeyes (I like this example) simply would ignore the magic cookie and pass no credentials to the server. Hence we get an error message 'No protocol specified Cannot open display'
The Xauthority file can be written in a way so that the hostname does not matter. We need to set the Authentication Family to 'FamilyWild'. I am not sure, if xauth has a proper command line for this, so here is an example that combines xauth and sed to do that. We need to change the first 16 bits of the nlist output. The value of FamilyWild is 65535 or 0xffff.
docker build -t xeyes - << __EOF__
FROM debian
RUN apt-get update
RUN apt-get install -qqy x11-apps
ENV DISPLAY :0
CMD xeyes
__EOF__
XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth
xauth nlist :0 | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
docker run -ti -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH -e XAUTHORITY=$XAUTH xeyes
invalidate cache in android studio will resolve this issue. Go to file-> click on invalidate cache/restart option.
data
is not an array, it is an object with an array of products so iterate over data.products
var allProducts = data.products.map(function (item) {
return new getData(item);
});
\
is an escape character in Python. \t
gets interpreted as a tab. If you need \
character in a string, you have to use \\
.
Your code should be:
test_file=open('c:\\Python27\\test.txt','r')
This would be work very fine
<a href="<%:Url.Action("Edit","Account",new { id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>
you can simply add a method (setAttributes, with "s" at the end) to "Element" prototype like:
Element.prototype.setAttributes = function(obj){
for(var prop in obj) {
this.setAttribute(prop, obj[prop])
}
}
you can define it in one line:
Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }
and you can call it normally as you call the other methods. The attributes are given as an object:
elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})
you can add an if statement to throw an error if the given argument is not an object.
Make sure the client computer has the same or higher version of the .NET framework that you built your program to.
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
Use the link http://ip-api.com/json. This will provide all the information as JSON. From this JSON content you can get the country easily. This site works using your current IP address. It automatically detects the IP address and sendback details.
This is what I got:
{
"as": "AS55410 C48 Okhla Industrial Estate, New Delhi-110020",
"city": "Kochi",
"country": "India",
"countryCode": "IN",
"isp": "Vodafone India",
"lat": 9.9667,
"lon": 76.2333,
"org": "Vodafone India",
"query": "123.63.81.162",
"region": "KL",
"regionName": "Kerala",
"status": "success",
"timezone": "Asia/Kolkata",
"zip": ""
}
N.B. - As this is a third-party API, do not use it as the primary solution. And also I am not sure whether it's free or not.
on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o
Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/ where new order is saved in some HMTL element. Then you submit the form with this data to some PHP script, and iterate trough it with for loop.
Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports
Apply port filter
Finally with the PID we can run the following command to kill the process
3) Copy PID from result set
Ex: taskkill /F /PID 189
Done !!! you can start your service now.
float only has a max. precision of 15 digits. Digits after the 15th position are therefore random, and conversion to bigint (max. 19 digits) or decimal does not help you.
This is not directly related to the initial issue, but probably will help somebody.
I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.
Bad example:
'ABC\username'
Good example:
'ABC\\username'
Restarting Visual Studio did the trick for me. I am using VS 2015.
If you are producing the DataTable
from an SQL query, have you considered simply using Dapper instead?
Then, instead of making a SqlCommand
with SqlParameters
and a DataTable
and a DataAdapter
and on and on, which you then have to laboriously convert to a class, you just define the class, make the query column names match the field names, and the parameters are bound easily by name. You already have the TankReading
class defined, so it will be really simple!
using Dapper;
// Below can be SqlConnection cast to DatabaseConnection, too.
DatabaseConnection connection = // whatever
IEnumerable<TankReading> tankReadings = connection.Query<TankReading>(
"SELECT * from TankReading WHERE Value = @value",
new { value = "tank1" } // note how `value` maps to `@value`
);
return tankReadings;
Now isn't that awesome? Dapper is very optimized and will give you darn near equivalent performance as reading directly with a DataAdapter
.
If your class has any logic in it at all or is immutable or has no parameterless constructor, then you probably do need to have a DbTankReading
class (as a pure POCO/Plain Old Class Object):
// internal because it should only be used in the data source project and not elsewhere
internal sealed class DbTankReading {
int TankReadingsID { get; set; }
DateTime? ReadingDateTime { get; set; }
int ReadingFeet { get; set; }
int ReadingInches { get; set; }
string MaterialNumber { get; set; }
string EnteredBy { get; set; }
decimal ReadingPounds { get; set; }
int MaterialID { get; set; }
bool Submitted { get; set; }
}
You'd use that like this:
IEnumerable<TankReading> tankReadings = connection
.Query<DbTankReading>(
"SELECT * from TankReading WHERE Value = @value",
new { value = "tank1" } // note how `value` maps to `@value`
)
.Select(tr => new TankReading(
tr.TankReadingsID,
tr.ReadingDateTime,
tr.ReadingFeet,
tr.ReadingInches,
tr.MaterialNumber,
tr.EnteredBy,
tr.ReadingPounds,
tr.MaterialID,
tr.Submitted
});
Despite the mapping work, this is still less painful than the data table method. This also lets you perform some kind of logic, though if the logic is any more than very simple straight-across mapping, I'd put the logic into a separate TankReadingMapper
class.
You didn't specify how the order is determined, but this will give you a rank value in MySQL:
SELECT t.*,
@rownum := @rownum +1 AS rank
FROM TBL_FOO t
JOIN (SELECT @rownum := 0) r
WHERE t.name = 'sarmen'
Then you can pick out what rows you want, based on the rank value.
simple way for new font awesome
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="txtSearch" >
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fas fa-search"></i></button>
</div>
</div>
Use the background-size
property: http://www.w3.org/TR/css3-background/#the-background-size
put values for each options like
<SELECT NAME="val">
<OPTION VALUE="1" value="1:2:3:4"> 1-4
<OPTION VALUE="2" value="5:6:7:8"> 5-8
<OPTION VALUE="3" value="9:10:11:12"> 9-12
</SELECT>
at server side in case of php, use functions like explode [array] = explode([delimeter],[posted value]);
$values = explode(':',$_POST['val']
the above code return an array have only the numbers and the ':' get removed
Just define <body onload="aFunction()">
that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }
.
ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.
Try this,
HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");
I am using VS2012 and facing the same error. I removed the following Target tag from the .csproj file and it started compiling without any error.
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
-- Error messages within Target Tag
</Target>
Excel.Application xl = new Excel.ApplicationClass();
Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
ws.Cells[1,1] = "Testing";
Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);
range.Merge(true);
range.Interior.ColorIndex =36;
xl.Visible =true;
for asp.net core 3.1
Response.Headers.Add("Refresh", "2");// in secound
and
Response.Headers.Remove("Refresh");
if you need copy local file to server (specify port )
scp -P 3838 /the/source/file [email protected]:/destination/file
Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).
Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder
. Or use Java's StringBuilder
explicitly.
Or use awk
for a single process without |
:
awk '/your_regexp/ && NR < 11' INPUTFILE
On each line, if your_regexp
matches, and the number of records (lines) is less than 11, it executes the default action (which is printing the input line).
Or use sed
:
sed -n '/your_regexp/p;10q' INPUTFILE
Checks your regexp and prints the line (-n
means don't print the input, which is otherwise the default), and quits right after the 10th line.
String value = new String(myString.getBytes("UTF-8"));
and, if you want to read from text file with "ISO-8859-1" encoded:
String line;
String f = "C:\\MyPath\\MyFile.txt";
try {
BufferedReader br = Files.newBufferedReader(Paths.get(f), Charset.forName("ISO-8859-1"));
while ((line = br.readLine()) != null) {
System.out.println(new String(line.getBytes("UTF-8")));
}
} catch (IOException ex) {
//...
}
Yes, here's an example:
CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )
You can INSERT into the table without indicating the createdDate and updatedDate columns:
INSERT INTO myTable (col1) VALUES (1)
Or use the keyword DEFAULT:
INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)
Then create a trigger for updating the updatedDate column:
CREATE TRIGGER dbo.updateMyTable
ON dbo.myTable
FOR UPDATE
AS
BEGIN
IF NOT UPDATE(updatedDate)
UPDATE dbo.myTable SET updatedDate=GETDATE()
WHERE col1 IN (SELECT col1 FROM inserted)
END
GO
I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).
The easiest solution that I have found is to do the following:
In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.
Example:
'use strict';
//my data variable that I need access to.
var data = null;
angular.module('sample', [])
Then in your controller:
.controller('SampleApp', function ($scope, $location) {
$scope.availableList = [];
$scope.init = function () {
$scope.availableList = data;
}
Finally, you have to init everything (order matters):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="/path/to/your/angular/js/sample.js"></script>
<script type="text/javascript">
data = <?= json_encode($cproducts); ?>
</script>
Finally initialize your controller and init function.
<div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">
By doing this you will now have access to whatever data you stuffed into the global variable.
to pass many options you can pass a object to a @Input decorator with custom data in a single line.
In the template
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
(selectedOption) = 'onOptionSelection($event)' >
{{opt.option}}
</li>
so in Directive class
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('myOptions') data;
//do something with data.first
...
// do something with data.second
}
You can pass input as ["apple","orange"]
if you want to leave the method as it is.
It worked for me with a similar method signature.
Consider the following code:
error_reporting(E_STRICT);
class test {
function test_arr(&$a) {
var_dump($a);
}
function get_arr() {
return array(1, 2);
}
}
$t = new test;
$t->test_arr($t->get_arr());
This will generate the following output:
Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
The reason? The test::get_arr()
method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr()
method returns an array value.
To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:
function test_arr($a) {
var_dump($a);
}
Since you can't change the signature of array_shift
you can also use an intermediate variable:
$inter = get_arr();
$el = array_shift($inter);
I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:
begin
merge into some_table st
using (select 'some' name, 'values' value from dual) v
on (st.name=v.name)
when matched then update set st.value=v.value
when not matched then insert (name, value) values (v.name, v.value);
end;
(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).
As it says at FontAwesome website FontAwesome =>
HTML:
<span class="icon login"></span> Login</li>
CSS:
.icon::before {
display: inline-block;
font-style: normal;
font-variant: normal;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
}
.login::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f007";
}
In .login::before
-> edit content:'';
to suit your unicode.
Wrap it in an unused function:
.f = function() {
## unwanted code here:
}
The VOLUME
command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.
The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.
You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from
command when you run a container.
The fundamental difference between VOLUME
and -v
is this: -v
will mount existing files from your operating system inside your docker container and VOLUME
will create a new, empty volume on your host and mount it inside your container.
Example:
VOLUME /var/lib/mysql
.some-volume
And then,
docker run --volumes-from some-volume docker-image-name:tag
some-volume
mounted in /var/lib/mysql
Note: Using --volumes-from
will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql
, it will be replaced with the contents of the volume.
I found the log file at /usr/local/var/log/postgres.log on a mac installation from brew.
This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.
if(arrayName && arrayName.length > 0){
//do something.
}
or thanks to tsemer's comment I added a second version
if(arrayName && arrayName.length)
Then I made a test for the second condition, using Scratchpad in Firefox:
var array1;_x000D_
var array2 = [];_x000D_
var array3 = ["one", "two", "three"];_x000D_
var array4 = null;_x000D_
_x000D_
console.log(array1);_x000D_
console.log(array2);_x000D_
console.log(array3);_x000D_
console.log(array4);_x000D_
_x000D_
if (array1 && array1.length) {_x000D_
console.log("array1! has a value!");_x000D_
}_x000D_
_x000D_
if (array2 && array2.length) {_x000D_
console.log("array2! has a value!");_x000D_
}_x000D_
_x000D_
if (array3 && array3.length) {_x000D_
console.log("array3! has a value!");_x000D_
}_x000D_
_x000D_
if (array4 && array4.length) {_x000D_
console.log("array4! has a value!");_x000D_
}
_x000D_
which also proves that if(array2 && array2.length)
and if(array2 && array2.length > 0)
are exactly doing the same
There is also another solution to the problem by implementing a layer-list that will act as the background for the LinearLayoout.
Add background_with_shadow.xml file to res/drawable
. Containing:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<corners android:radius="5dp"/>
</shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="2dp">
<shape
android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
Then add the the layer-list as background in your LinearLayout.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background_with_shadow"/>
sklearn.cross_validation
is deprecated since version 0.18, instead you should use sklearn.model_selection
as show below
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
There is a simple solution, So when you run Object.keys(Enum)
that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.
enum Enum {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN
}
const keys = Object.keys(Enum);
console.log(keys.slice(keys.length / 2));
Go to the Customize section on Bootstrap site and choose the size you prefer. You'll have to set @gridColumnWidth
and @gridGutterWidth
variables.
For example: @gridColumnWidth = 65px
and @gridGutterWidth = 20px
results on a 1000px
layout.
Then download it.
A big change that happened with Xcode 8 Beta 6 for Swift 3 was that id now imports as Any
rather than AnyObject
.
This means that parsedData
is returned as a dictionary of most likely with the type [Any:Any]
. Without using a debugger I could not tell you exactly what your cast to NSDictionary
will do but the error you are seeing is because dict!["currently"]!
has type Any
So, how do you solve this? From the way you've referenced it, I assume dict!["currently"]!
is a dictionary and so you have many options:
First you could do something like this:
let currentConditionsDictionary: [String: AnyObject] = dict!["currently"]! as! [String: AnyObject]
This will give you a dictionary object that you can then query for values and so you can get your temperature like this:
let currentTemperatureF = currentConditionsDictionary["temperature"] as! Double
Or if you would prefer you can do it in line:
let currentTemperatureF = (dict!["currently"]! as! [String: AnyObject])["temperature"]! as! Double
Hopefully this helps, I'm afraid I have not had time to write a sample app to test it.
One final note: the easiest thing to do, might be to simply cast the JSON payload into [String: AnyObject]
right at the start.
let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! Dictionary<String, AnyObject>
First, {"value": .value} can be abbreviated to just {value}.
Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.
Putting these together, the two objects in the two files can be combined in the specified way as follows:
$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'
The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.
The jq manual deprecates --argfile
because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.
If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile
does not incur the inefficiencies of the -s
command-line option when the latter is used with multiple files.
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity
attribute.Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.
(Current docs here)
A TableLayout consists of a number of
TableRow
objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.The width of a column is defined by the row with the widest cell in that column.
Note: Absolute Layout is deprecated.
Try this
$_SERVER['HTTP_CF_CONNECTING_IP'];
instead of
$_SERVER["REMOTE_ADDR"];
Probably the easiest way would be use this app Hosts Editor . You need to have root
Yep :
Thread t = new Thread (new ParameterizedThreadStart(myMethod));
t.Start (myParameterObject);
<ul>
<li ng-repeat="item in items | filter:keyword as filteredItems">
...
</li>
<li ng-if="filteredItems.length===0">
No items found
</li>
</ul>
This is similar to @Konrad 'ktoso' Malawski but slightly easier to remember.
Tested with Angular 1.4
The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011
SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;
The result : 2011-05-00
Try using varchar2 instead of varchar and use this :
INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
It might be useful.
Just type this into your command prompt while cd your/package/src/
go get github.com/go-gl/[email protected]
You get specific revision of package in question right into your source code, ready to use in import statement.
Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.
HTML:
<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />
JavaScript:
var counter = 0;
$("#SubtractDay").click(function() {
counter--;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
counter++;
var today = new Date();
today.setDate(today.getDate() + counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
$("#dateChange").val(d + "/" + m + "/" + y);
});
Change the signature of the CreateFile
method to expect a SupportedPermissions
value instead of plain Enum.
public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions
};
return file.Id;
}
Then when you call your method you pass the SupportedPermissions
value to your method
var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);
Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Example::Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.
Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/yourname/full-backup
In your case, for 2.30PM
,
30 14 * * * YOURCMD
To know more about cron, visit this website.
This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.
TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.
Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.
substring
is definitely best, but here's one strsplit
alternative, since I haven't seen one yet.
> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"
or equivalently
> unlist(strsplit(x, ''))[1]
## [1] "h"
And you can paste
the rest of the string back together.
> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"
Your User object is linked to the Group object through a ManyToMany relationship.
You can thereby apply the filter method to user.groups.
So, to check if a given User is in a certain group ("Member" for the example), just do this :
def is_member(user):
return user.groups.filter(name='Member').exists()
If you want to check if a given user belongs to more than one given groups, use the __in operator like so :
def is_in_multiple_groups(user):
return user.groups.filter(name__in=['group1', 'group2']).exists()
Note that those functions can be used with the @user_passes_test decorator to manage access to your views :
from django.contrib.auth.decorators import login_required, user_passes_test
@login_required
@user_passes_test(is_member) # or @user_passes_test(is_in_multiple_groups)
def myview(request):
# Do your processing
Hope this help
Several problems arise in this question.
Problem #1 - css Specificity (how to override important rule).
According to specification - to override this selector your selector should be 'stronger' which mean it should be!important and have at least 1 id, 1 class and something else - according to you creating this selector is impossible(as you can't alter page content). So the only possible option is to put something into element style which (could be done with js). Note: style rule should also have !important to override.
Problem #2 - background is not a single property - it is a set of properties (see specification)
So you really need to know what are exact names of properties you want to change (in your case it would be background-image)
Problem #3 - How to remove rule already applied (to get previous value)?
Unfortunately css have no mechanism to dismiss rule which qualify for an element - only to override with "stronger" rule. So you won't be able to solve this task with just setting value to something like 'inherit' or 'default' cause value you want to see is neither inherit from parent nor default. To solve this problem you have couple of options.
1) You may already know what is the value you want to apply. For example you can find out this value based on selector used. So in this case you may know that for selector ".image-list li" you need background-image: url("http://placekitten.com/150/50"). If so - just you this script:
jQuery(".image-list li").attr('style', 'background-image: url("http://placekitten.com/150/50") !important; ');
2) If you don't know the value then you can try to alter page content in such a way, that rule you want to dismiss is no longer qualify for element, whereas rule you want to be shown - still qualify. In this case you may temporary remove id from container element. Here is the code:
jQuery("#an-element").attr('id', '');
var backgroundImage = jQuery(".image-list li").css('background-image');
jQuery("#an-element").attr('id', 'an-element');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');
Here is link to fiddle http://jsfiddle.net/o3jn9mzo/
3) As third solution - you may generate element which will qualify for desired selection to find out property value - something like this:
var backgroundImage = jQuery("<div class='image-list'><li></li></div>").find('li').css('background-image');
jQuery(".image-list li").attr('style', 'background-image: ' + backgroundImage + ' !important; ');
P.S.: Sorry for really late response.
Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.
Try this query:
DELETE WorkRecord2, Employee
FROM WorkRecord2
INNER JOIN Employee ON (tbl_name.EmployeeRun=tbl_name.EmployeeNo)
WHERE tbl_name.Company = '1'
AND tbl_name.Date = '2013-05-06';
git push --delete origin $TAGNAME
is the correct approach (in addition of a local delete).
But: make sure to use Git 2.31.
"git push $there --delete
"(man) should have been diagnosed as an error, but instead turned into a matching push, which has been corrected with Git 2.31 (Q1 2021).
See commit 20e4164 (23 Feb 2021) by Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit 1400458, 25 Feb 2021)
push
: do not turn --delete '' into a matching pushNoticed-by: Tilman Vogel
When we added a syntax sugar "
git push remote --delete
"(man)<ref>
to "git push
"(man) as a synonym to the canonicalgit push remote
(man) : syntax at f517f1f ("builtin-push
:add
(man)--delete
as syntactic sugar for :foo", 2009-12-30, Git v1.7.0-rc0 -- merge), we weren't careful enough to make sure that<ref>
is not empty.Blindly rewriting "--delete " to ":" means that an empty string
<ref>
results in refspec ":", which is the syntax to ask for "matching" push that does not delete anything.Worse yet, if there were matching refs that can be fast-forwarded, they would have been published prematurely, even if the user feels that they are not ready yet to be pushed out, which would be a real disaster.
-(IBAction)Method
{
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[ViewMain addGestureRecognizer:panRecognizer];
[panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [recognizer velocityInView:self.view];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
[UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
}
Simply call
print(unknownDataType.runtimeType)
on the data.
It is mentioned under "Index expressions".
An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
v, ok = a[x] v, ok := a[x] var v, ok = a[x]
yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.
Would not that have to be:
.replaceAll("\"","\\\\\"")
FIVE backslashes in the replacement String.
Yes, orWhereIn
is a method that you can use.
I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode
to create a string and then explode it (this is a guess at your array structure):
$values = implode(',', array_map(function($value)
{
return trim($value, ',');
}, $filters));
$query->whereIn('products.value', explode(',' $values));
You can use disabled attribute to disable the textbox.
document.getElementById('color').disabled = true;
executePendingTransactions()
, commitNow()
not worked (
Worked in androidx (jetpack).
private final FragmentManager fragmentManager = getSupportFragmentManager();
public void removeFragment(FragmentTag tag) {
Fragment fragmentRemove = fragmentManager.findFragmentByTag(tag.toString());
if (fragmentRemove != null) {
fragmentManager.beginTransaction()
.remove(fragmentRemove)
.commit();
// fix by @Ogbe
fragmentManager.popBackStackImmediate(tag.toString(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
Add a <version>
element after the <plugin>
<artifactId>
in your pom.xml
file. Find the following text:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
Add the version tag to it:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
The warning should be resolved.
Regarding this:
'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing
Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version>
tag as shown above.
To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---
Take that version number (as in the 2.3.2
above) and add it to your POM, as shown.
You can add a hook function to intercept all calls to addEventHandler
. The hook will push the handler to a list that can be used for cleanup. For example,
if (EventTarget.prototype.original_addEventListener == null) {
EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;
function addEventListener_hook(typ, fn, opt) {
console.log('--- add event listener',this.nodeName,typ);
this.all_handlers = this.all_handlers || [];
this.all_handlers.push({typ,fn,opt});
this.original_addEventListener(typ, fn, opt);
}
EventTarget.prototype.addEventListener = addEventListener_hook;
}
You should insert this code near the top of your main web page (e.g. index.html
). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.
For example,
function cleanup(elem) {
for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
elem[t] = null;
console.log('cleanup removed listener from '+elem.nodeName,t);
}
for (let t of elem.all_handlers || []) {
elem.removeEventListener(t.typ, t.fn, t.opt);
console.log('cleanup removed listener from '+elem.nodeName,t.typ);
}
}
Note: for IE use Element instead of EventTarget, and change => to function, and various other things.
If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.
Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.
code example:
// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3); // Use word trigrams
String[] tokens1 = "This is a short example text .".split(" ");
String[] tokens2 = "A short example text could look like that .".split(" ");
double score = measure.getSimilarity(tokens1, tokens2);
System.out.println("Similarity: " + score);
The Wikipedia page on sorting algorithms has a great comparison chart.
http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
I encountered this problem today and eventually I realize it was the comment on the line before the mysql dll's that was causing the problem.
This is what you should have in php.ini by default for PHP 5.5.16:
;extension=php_exif.dll Must be after mbstring as it depends on it
;extension=php_mysql.dll
;extension=php_mysqli.dll
Besides removing the semi-colons, you also need to delete the line of comment that came after php_exif.dll. This leaves you with
extension=php_exif.dll
extension=php_mysql.dll
extension=php_mysqli.dll
This solves the problem in my case.
You can call private methods.
If you encountered the following error:
expect(new FooBar(/*...*/).initFooBar()).toEqual(/*...*/);
// TS2341: Property 'initFooBar' is private and only accessible within class 'FooBar'
// @ts-ignore
:// @ts-ignore
expect(new FooBar(/*...*/).initFooBar()).toEqual(/*...*/);
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.
In foo.cc:
#include <cstdio> // for puts
#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"
int main(int argc, const char* argv[])
{
puts("Hello!");
bar();
zoo();
puts(Message::third);
return 0;
}
In messages.hh:
#ifndef MESSAGES_HH
#define MESSAGES_HH
namespace Message {
char const * const first = "Yes, this is the first message!";
char const * const second = "This is the second message.";
char const * const third = "Message #3.";
};
#endif
In bar.cc:
#include "messages.hh"
#include <cstdio>
void bar(void)
{
puts("Wow!");
printf("bar: %s\n", Message::first);
}
In zoo.cc:
#include <cstdio>
#include "messages.hh"
void zoo(void)
{
printf("zoo: %s\n", Message::second);
}
In bar.hh:
#ifndef BAR_HH
#define BAR_HH
#include "messages.hh"
void bar(void);
#endif
In zoo.hh:
#ifndef ZOO_HH
#define ZOO_HH
#include "messages.hh"
void zoo(void);
#endif
This yields the following output:
Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.
The data type char const * const
means a constant pointer to an array of constant characters. The first const
is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const
is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the const
s, but then the source code is less portable.
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
SQL Server may also return this error if the service account does not have permission to read the file being imported. Ensure that the service account has read access to the file location. For example:
icacls D:\ImportFiles /Grant "NT Service\MSSQLServer":(OI)(CI)R
$@
is all of the parameters passed to the script.
For instance, if you call ./someScript.sh foo bar
then $@
will be equal to foo bar
.
If you do:
./someScript.sh foo bar
and then inside someScript.sh
reference:
umbrella_corp_options "$@"
this will be passed to umbrella_corp_options
with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.
#include <boost/version.hpp>
#include <iostream>
#include <iomanip>
int main()
{
std::cout << "Boost version: "
<< BOOST_VERSION / 100000
<< "."
<< BOOST_VERSION / 100 % 1000
<< "."
<< BOOST_VERSION % 100
<< std::endl;
return 0;
}
Update: the answer has been fixed.
Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.
See this question and answer: AngularJS dependency injection of value inside of module.config
A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql
This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.
This depends on what's actually being added by the pseudoselectors. In your situation, setting content to ""
will get rid of it, but if you're setting borders or backgrounds or whatever, you need to zero those out specifically. As far as I know, there's no one cure-all for removing everything about a before/after element regardless of what it is.
There are some quirks to be aware of here.
HTMLIFrameElement.contentWindow
is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window
object.
You can also try HTMLIFrameElement.contentDocument.defaultView
, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window
object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.
window.frames['name']
returning the window is the oldest and hence most reliable interface. But you then have to use a name="..."
attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..."
would be better but IE doesn't like that.)
window.frames[number]
is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.
It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent
script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.
Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.
First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.
Then, the convention:
And that's it.
It gives
class MyClass {
enum TheEnumeration {
FIRST_ELEMENT,
SECOND_ELEMENT,
}
int class_variable;
int MyMethod(int first_param, int second_parameter) {
int local_variable;
TheEnumeration local_enum;
for(int myindex=0, myindex<class_variable, myindex++) {
localEnum = FIRST_ELEMENT;
}
}
}
The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.
Here is my workaround for this:
Set you SSLSocketFactory as default:
HttpsURLConnection.setDefaultSSLSocketFactory(...);
For Apache CXF which I use you need also add these lines to your config:
<http-conf:conduit name="*.http-conduit">
<http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>
var path = location.pathname
returns the path of the current URL (jQuery is not needed). The use of window.location
is optional.
The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class file. Given that all methods in an interface are abstract, the VM would have to look for a particular implementation of the interface in order to find the code behind the static method so that it could be executed. This then contradicts how static method resolution works and would introduce an inconsistency into the language.
It doesn't need to be complicated:
val = df.loc[df.wd==1, 'col_name'].values[0]
What you need is nm
and its -D
option:
$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
U atanf
U calloc
.
.
.
Exported sumbols are indicated by a T
. Required symbols that must be loaded from other shared objects have a U
. Note that the symbol table does not include just functions, but exported variables as well.
See the nm
manual page for more information.
Wamp server share in local network
Reference Link: http://forum.aminfocraft.com/blog/view/141/wamp-server-share-in-local-netword
Edit your Apache httpd.conf:
Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all
and
#onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
#Deny from all
to share mysql server:
edit wamp/alias/phpmyadmin.conf
<Directory "E:/wamp/apps/phpmyadmin3.2.0.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
#Deny from all
Allow from all
If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock
Click in the grid so it has focus.
Ctrl+End
This will force the rest of the records back into the grid.
All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/
This is what I use:
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
You can apply this function on your text :
$yourtext = iconv('UTF-8', 'windows-1252', $yourtext);
Thanks
Quoting the Pandas docs
pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.
So, the Series is the data structure for a single column of a DataFrame
, not only conceptually, but literally, i.e. the data in a DataFrame
is actually stored in memory as a collection of Series
.
Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.
They both have extremely similar APIs, but you'll find that DataFrame
methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series
(or equivalent object) to a DataFrame
, while adding a Series
to another Series
involves creating a DataFrame
.