You may want to use the onLoad
event, as in the following example:
<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>
The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)
If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location
, as in the following example:
<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
Check your code man....
In the main method you are trying to remove the 4th element which is not there and hence the error. In the remove() method you are trying to remove the 3rd element which is there and hence no error.
If your if statement is in Loop You can use
break;
If you want to escape some code & continue to loop Use :
continue;
If your if statement not in Loop You can use :
return 0;
Or
exit();
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
This is the example for where I have removed the character - from the String.
I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:
The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.
But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:
a. For simple DOM manipulation, use jQuery chaining and traversing, $("#content").html('something').end().find(whatever)....
b. If you'd like to do something else, employ jQuery's bind
with custom event and triggerHandler
$("#content").html('something').triggerHandler('customAction');
$('#content').unbind().bind('customAction', function(event, data) {
//Custom-action
});
Here's a link to jQuery trigger handler: http://api.jquery.com/triggerHandler/
<
= less than <
, >
= greater than >
If your Objects
are containing of Strings
only, then you can do it like this:
Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(entry.getValue() instanceof String){
newMap.put(entry.getKey(), (String) entry.getValue());
}
}
If every Objects
are not String
then you can replace (String) entry.getValue()
into entry.getValue().toString()
.
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
Find the text view from the layout.
val textView : TextView = findViewById(R.id.android_text) as TextView
Setting onClickListener on the textview.
textview.setOnClickListener(object: View.OnClickListener {
override fun onClick(view: View): Unit {
// Code here.
textView.text = getString(R.string.name)
}
})
Argument parentheses can be omitted from View.setOnClickListener if we pass a single function literal argument. So, the simplified code will be:
textview.setOnClickListener {
// Code here.
textView.text = getString(R.string.name)
}
I tried to implement the result of Nick which is:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:
$("#modal_popup").html(data);
$("#modal_popup").dialog('option', 'title', 'My New Title');
$("#modal_popup").dialog({ width: 950, height: 550);
I fixed this by adding the title to the javascript function arguments of each dialog on the page:
function show_popup1() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}
function show_popup2() {
$("#modal_popup").html(data);
$("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}
Performance is based on the amount of data you are executing on...
If it is less data around 20k. JOIN works better.
If the data is more like 100k+ then IN works better.
If you do not need the data from the other table, IN is good, But it is alwys better to go for EXISTS.
All these criterias I tested and the tables have proper indexes.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
I've the same problem, and the below solution exactly work for me....!
Edit eclipse.ini
file and remove these two lines:
--launcher.library
.%%..\eclipse\plugins\eclipse\plugins\org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813
Make sure make a separate copy of this file before any changing...:)
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
I dont think python has a catch :)
try:
connection = manager.connect("I2Cx")
except Exception, e:
print e
Brief and simple
It is a function which returns another function written in short way.
const handleChange = field => e => {
e.preventDefault()
// Do something here
}
// is equal to
function handleChange(field) {
return function(e) {
e.preventDefault()
// Do something here
}
}
Why people do it ?
Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.
For example we have a button
with onClick callback. And we need to pass id
to the function, but onClick
accepts only one parameter event
, we can not pass extra parameters within like this:
const handleClick = (event, id) {
event.preventDefault()
// Dispatch some delete action by passing record id
}
It will not work!
Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .
Below the function handleClick(props.id)}
will be called and return a function and it will have id
in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.
const handleClick = id => event {
event.preventDefault()
// Dispatch some delete action by passing record id
}
const Confirm = props => (
<div>
<h1>Are you sure to delete?</h1>
<button onClick={handleClick(props.id)}>
Delete
</button>
</div
)
Other benefit
A function which returns another function also called "curried functions" and they are used for function compositions.
You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47
Clean function can be called from VBA this way:
Range("A1").Value = Application.WorksheetFunction.Clean(Range("A1"))
However as written here, the CLEAN function was designed to remove the first 32 non-printing characters in the 7 bit ASCII code (values 0 through 31) from text. In the Unicode character set, there are additional nonprinting characters (values 127, 129, 141, 143, 144, and 157). By itself, the CLEAN function does not remove these additional nonprinting characters.
Rick Rothstein have written code to handle even this situation here this way:
Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
Dim X As Long, CodesToClean As Variant
CodesToClean = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, _
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 129, 141, 143, 144, 157)
If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
For X = LBound(CodesToClean) To UBound(CodesToClean)
If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
Next
CleanTrim = WorksheetFunction.Trim(S)
End Function
:active
denotes the interaction state (so for a button will be applied during press), :focus
may be a better choice here. However, the styling will be lost once another element gains focus.
The final potential alternative using CSS would be to use :target
, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.
.active:active {_x000D_
color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
color: red;_x000D_
}_x000D_
:target {_x000D_
color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery
$('button').on('click', function(){_x000D_
$('button').removeClass('selected');_x000D_
$(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
_x000D_
A really simple option that works with any website where you can upload Javascript is www.multilingualizer.com
It lets you put all text for all languages onto one page and then hides the languages the user doesn't need to see. Works well.
You need to use the android:background property , eg
android:background="@color/white"
Also you need to add a value for white in the strings.xml
<color name="white">#FFFFFF</color>
Edit : 18th Nov 2012
The first two letters of an 8 letter color code provide the alpha value, if you are using the html 6 letter color notation the color is opaque.
Eg :
Since version 0.15.0
this can now be easily done using .dt
to access just the date component:
df['just_date'] = df['dates'].dt.date
The above returns a datetime.date
dtype, if you want to have a datetime64
then you can just normalize
the time component to midnight so it sets all the values to 00:00:00
:
df['normalised_date'] = df['dates'].dt.normalize()
This keeps the dtype
as datetime64
, but the display shows just the date
value.
I am providing an answer from my own blog. Hope this will help.
What will be output?
Following XML file named users.xml will be created.
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<users>
<user uid="1">
<firstname>Interview</firstname>
<lastname>Bubble</lastname>
<email>[email protected]</email>
</user>
</users>
PROCEDURE
Basic steps, in order to create an XML File with a DOM Parser, are:
Create a DocumentBuilder
instance.
Create a Document from the above DocumentBuilder
.
Create the elements you want using the Element
class and its appendChild
method.
Create a new Transformer
instance and a new DOMSource
instance.
Create a new StreamResult
to the output stream you want to use.
Use transform
method to write the DOM object to the output stream.
SOURCE CODE:
package com.example.TestApp;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXMLFileJava {
public static void main(String[] args) throws ParserConfigurationException,
IOException,
TransformerException
{
// 1.Create a DocumentBuilder instance
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbuilder = dbFactory.newDocumentBuilder();
// 2. Create a Document from the above DocumentBuilder.
Document document = dbuilder.newDocument();
// 3. Create the elements you want using the Element class and its appendChild method.
// root element
Element users = document.createElement("users");
document.appendChild(users);
// child element
Element user = document.createElement("user");
users.appendChild(user);
// Attribute of child element
user.setAttribute("uid", "1");
// firstname Element
Element firstName = document.createElement("firstName");
firstName.appendChild(document.createTextNode("Interview"));
user.appendChild(firstName);
// lastName element
Element lastName = document.createElement("lastName");
lastName.appendChild(document.createTextNode("Bubble"));
user.appendChild(lastName);
// email element
Element email = document.createElement("email");
email.appendChild(document.createTextNode("[email protected]"));
user.appendChild(email);
// write content into xml file
// 4. Create a new Transformer instance and a new DOMSource instance.
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
// 5. Create a new StreamResult to the output stream you want to use.
StreamResult result = new StreamResult(new File("/Users/admin/Desktop/users.xml"));
// StreamResult result = new StreamResult(System.out); // to print on console
// 6. Use transform method to write the DOM object to the output stream.
transformer.transform(source, result);
System.out.println("File created successfully");
}
}
OUTPUT:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
<user uid="1">
<firstName>Interview</firstName>
<lastName>Bubble</lastName>
<email>[email protected]</email>
</user>
</users>
As mentioned, you can use:
=Format(Fields!Price.Value, "C")
A digit after the "C" will specify precision:
=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")
You can also use Excel-style masks like this:
=Format(Fields!Price.Value, "#,##0.00")
Haven't tested the last one, but there's the idea. Also works with dates:
=Format(Fields!Date.Value, "yyyy-MM-dd")
This will do it for you:
=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")
Given this function in the column to the right of the names (which are in column C), the result is:
Romney
Gingrich 1
Obama 1
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %>
things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib
and declare the needed taglibs in top of JSP). It has a <c:forEach>
tag which can iterate over among others Map
s. Every iteration will give you a Map.Entry
back which in turn has getKey()
and getValue()
methods.
Here's a basic example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet
or a ServletContextListener
to place the ${countries}
in the desired scope. If this list is supposed to be request-based, then use the Servlet
's doGet()
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener
's contextInitialized()
so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries
will be available in EL by ${countries}
.
Hope this helps.
Finalize
protected
, not public
or private
so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize
methodDispose
IDisposable
on every type that has a finalizerDispose
method. In other words, avoid using an object after the Dispose
method has been called on it.Dispose
on all IDisposable
types once you are done with themDispose
to be called multiple times without raising errors.Dispose
method using the GC.SuppressFinalize
methodDispose
methodsDispose/Finalized Pattern
Dispose
and Finalize
when working with unmanaged resources. The Finalize
implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose
method explicitly.Finalize
method as well as Dispose
method. Additionally call the Dispose
method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose
method.list_methods - generates the methods for add, removing, counting, and contains for a list
public void add${listname}(${listtype} toAdd){
get${listname}s().add(toAdd);
}
public void remove${listname}(${listtype} toRemove){
get${listname}s().remove(toRemove);
}
public ${listtype} get${listname}(int index){
return get${listname}s().get(index);
}
public int get${listname}Count(){
return get${listname}s().size();
}
public boolean contains${listname}(${listtype} toFind){
return get${listname}s().contains(toFind);
}
${cursor}
id - inserts the annotations, imports, field, and getter for simple JPA @Id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Long getId(){
return id;
}
${cursor}
${:import (javax.persistence.GenerationType,javax.persistence.GeneratedValue,javax.persistence.Id)}
Create a static constructor to add values in the Dictionary
enum Commands
{
StudentDetail
}
public static class Quires
{
public static Dictionary<Commands, String> quire
= new Dictionary<Commands, String>();
static Quires()
{
quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
}
}
If you're willing to use LLVM, check this out: http://llvm.org/docs/tutorial/. It teaches you how to write a compiler from scratch using LLVM's framework, and doesn't assume you have any knowledge about the subject.
The tutorial suggest you write your own parser and lexer etc, but I advise you to look into bison and flex once you get the idea. They make life so much easier.
If you have already installed Visual Studio Build Tools (as in other comments), and upgraded setuptools but it still doesn't work:
Make sure to run pip under x86 or x64 Native Tools Command Prompt.
It can be found under VS folder in Windows start menu. The default command line prompt may NOT provide Pip the path to the VS build tool, as is in my case.
There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.
HTML:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="myButton" />
</form>
JavaScript:
$(document).ready(function() {
$('#myButton').click(function() {
foo($('#formValueId').val());
});
});
A lot of responses on here are addressing the how but not the why. PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript. To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers. I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.
ES6 contains inbuilt method (includes
) in String's prototype
, which can be used to check if string contains another string or not.
var str = 'To be, or not to be, that is the question.';_x000D_
_x000D_
console.log(str.includes('To be'));
_x000D_
Following polyfill can be used to add this method in non-supported browsers. (Source)
if (!String.prototype.includes) {_x000D_
String.prototype.includes = function(search, start) {_x000D_
'use strict';_x000D_
if (typeof start !== 'number') {_x000D_
start = 0;_x000D_
}_x000D_
_x000D_
if (start + search.length > this.length) {_x000D_
return false;_x000D_
} else {_x000D_
return this.indexOf(search, start) !== -1;_x000D_
}_x000D_
};_x000D_
}
_x000D_
An answer for experts only:
List<Integer> ints = ...;
String all = new ArrayList<Integer>(ints).toString();
String[] split = all.substring(1, all.length()-1).split(", ");
List<String> strs = Arrays.asList(split);
Change [
to [[
, and ]
to ]]
.
The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.
I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented
native events from occurring with:
<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
:checked="confirmed.indexOf(render.uuid) > -1"
:value="render.uuid"
/>
removing the .prevent
from the @click
handler fixed my issue.
Neither of the posted answers worked for me. Setting position: absolute
for the child element did work however.
If you want to delete rows based on multiple values of the column, you could use:
df[(df.line_race != 0) & (df.line_race != 10)]
To drop all rows with values 0 and 10 for line_race
.
If you are using a windows machine with Excel spreadsheet loaded, the new mySql plugin to Excel is phenomenal. The folks at Oracle really did a nice job on that software. You can make the database connection directly from Excel. That plugin will analyse your data, and set up the tables for you in a format consistent with the data. I had some monster big csv files of data to convert. This tool was a big time saver.
http://dev.mysql.com/downloads/windows/excel/
You can make updates from within Excel that will populate to the database online. This worked exceedingly well with mySql files created on ultra inexpensive GoDaddy shared hosting. (Note when you create the table at GoDaddy, you have to select some off-standard settings to enable off site access of the database...)
With this plugin you have pure interactivity between your XL spreadsheet and online mySql data storage.
For portability to pre-Bash 3.1 (when the =~
test was introduced), use expr
.
if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
echo "String is a valid integer."
else
echo "String is not a valid integer."
fi
expr STRING : REGEX
searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \
. -\?
means "maybe -
", [0-9]\+
means "one or more digits", and $
means "end of string".
Bash also supports extended globs, though I don't recall from which version onwards.
shopt -s extglob
case "$string" of
@(-|)[0-9]*([0-9]))
echo "String is a valid integer." ;;
*)
echo "String is not a valid integer." ;;
esac
# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]
@(-|)
means "-
or nothing", [0-9]
means "digit", and *([0-9])
means "zero or more digits".
main.cpp doesn't have to know what is in class.cpp. It just has to know the declarations of the functions/classes that it goes to use, and these declarations are in class.h.
The linker links between the places where the functions/classes declared in class.h are used and their implementations in class.cpp
X display location : localhost:0 Worked for me :)
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
To start server locally paste the below code in package.json and run npm start in command line.
"scripts": {
"start": "http-server -c-1 -p 8081"
},
Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.
A one-liner:
var encodedMsg = $('<div />').text(message).html();
See it work:
All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!
ContextCompat.getDrawable(mContext, drawable)
From documented method
public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id
You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n)
, although it can end up O(n²)
on a bad day.
Here's an implementation with a randomly chosen pivot:
import random
def select_nth(n, items):
pivot = random.choice(items)
lesser = [item for item in items if item < pivot]
if len(lesser) > n:
return select_nth(n, lesser)
n -= len(lesser)
numequal = items.count(pivot)
if numequal > n:
return pivot
n -= numequal
greater = [item for item in items if item > pivot]
return select_nth(n, greater)
You can trivially turn this into a method to find medians:
def median(items):
if len(items) % 2:
return select_nth(len(items)//2, items)
else:
left = select_nth((len(items)-1) // 2, items)
right = select_nth((len(items)+1) // 2, items)
return (left + right) / 2
This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort
) because that's really fast. I've tried before and I lost.
df.drop(labels=df[df.index % 3 != 0].index, axis=0) # every 3rd row (mod 3)
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
Some of these examples are more complicated than you might need. To remove a single slash, from anywhere (leading or trailing), you could get away with something as simple as this:
let no_trailing_slash_url = site.replace('/', '');
Complete example:
let site1 = "www.somesite.com";
let site2 = "www.somesite.com/";
function someFunction(site)
{
let no_trailing_slash_url = site.replace('/', '');
return no_trailing_slash_url;
}
console.log(someFunction(site2)); // www.somesite.com
Note that .replace(...)
returns a string, it does not modify the string it is called on.
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
You can find the full list here.
\t
Insert a tab in the text at this point.\b
Insert a backspace in the text at this point.\n
Insert a newline in the text at this point.\r
Insert a carriage return in the text at this point.\f
Insert a formfeed in the text at this point.\'
Insert a single quote character in the text at this point.\"
Insert a double quote character in the text at this point.\\
Insert a backslash character in the text at this point.Depending on your URL scheme, you can make the UTF-8 encoded part "not important". For example, if you look at Stack Overflow URLs, they're of the following form:
http://stackoverflow.com/questions/2742852/unicode-characters-in-urls
However, the server doesn't actually care if you get the part after the identifier wrong, so this also works:
http://stackoverflow.com/questions/2742852/?????????????????
So if you had a layout like this, then you could potentially use UTF-8 in the part after the identifier and it wouldn't really matter if it got garbled. Of course this probably only works in somewhat specialised circumstances...
1) Your Express project filesystem maybe like:
/ ...
/lib
/node_modules
/public
/views
app.js
config.json
package.json
app.js - you global app container
2) Module main file (lib/mymodule/index.js):
var express = require('express');
var app = module.exports = express();
// and load module dependencies ...
// this place to set module settings
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
// then do module staff
app.get('/mymodule/route/',function(req,res){ res.send('module works!') });
3) Connect module in main app.js
...
var mymodule = require('mymodule');
app.use(mymodule);
4) Sample logic
lib/login
lib/db
lib/config
lib/users
lib/verify
lib/
/api/
...
lib/
/admin/
/users/
/settings/
/groups/
...
tj says/show on Vimeo interesting idea how modularize express application - Modular web applications with Node.js and Express. Powerful and simple.
Abstract:
The reason why you are getting this error
message is because you are trying to call a method on an int
type of a variable. This would work if would have called len()
function on a list
type of a variable. Let's examin the two cases:
Fail:
num = 10
print(len(num))
The above will produce an error similar to yours due to calling len()
function on an int
type of a variable;
Success:
data = [0, 4, 8, 9, 12]
print(len(data))
The above will work since you are calling a function on a list
type of a variable;
Use this:
<link onclick='doWithThisElement(this.attributes["id"].value)' />
In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).
If you want to run the script in a linux kickstart you have to run as below .
sh /tmp/script.sh > /dev/null 2>&1 < /dev/null &
John Woo's answer is correct, as far as it goes. Here are a few additional points.
A primary key is always one of the candidate keys. Fairly often, it's the only candidate.
A table with no candidate keys does not represent a relation. If you're using the relational model to help you build a good database, then every table you design will have at least one candidate key.
The relational model would be complete without the concept of primary key. It wasn't in the original presentation of the relational model. As a practical matter, the use of foreign key references without a declared primary key leads to a mess. It could be a logically correct mess, but it's a mess nonetheless. Declaring a primary key lets the DBMS help you enforce the data rules. Most of the time, having the DBMS help you enforce the data rules is a good thing, and well worth the cost.
Some database designers and some users have some mental confusion about whether the primary key identifies a row (record) in a table or an instance of an entity in the subject matter that the table represents. In an ideal world, it's supposed to do both, and there should be a one-for-one correspondence between rows in an entity table and instances of the corresponding entity.
In the real world, things get screwed up. Somebody enters the same new employee twice, and the employee ends up with two ids. Somebody gets hired, but the data entry slips through the cracks in some manual process, and the employee doesn't get an id, until the omission is corrected. A database that does not collapse the first time things get screwed up is more robust than one that does.
Neither collection will let you add items that way.
You can make an extension to make for examle List(Of String)
have an Add
method that can do that:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
For Each s As String In values
list.Add(s)
Next
End Sub
End Module
Now you can add multiple value in one call:
Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)
Just to correct mingos' answer:
If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.
Example:
Instead of:
document.cookie = "cookie_name=cookie_value; 0; path=/";
Just write:
document.cookie = "cookie_name=cookie_value; path=/";
A segfault is accessing memory that you're not allowed to access. It's read-only, you don't have permission, etc...
A bus error is trying to access memory that can't possibly be there. You've used an address that's meaningless to the system, or the wrong kind of address for that operation.
I had same problem, but solved.
I removed the following line in .bashrc
alias do="docker.exe" # this line caused the problem
I use WSL(windows subsystem for linux)
Ok, this is not really an answer to the question, but if you are looking up how to make your own delegate maybe something far simpler could be a better answer for you.
I hardly implement my delegates because I rarely need. I can have ONLY ONE delegate for a delegate object. So if you want your delegate for one way communication/passing data than you are much better of with notifications.
NSNotification can pass objects to more than one recipients and it is very easy to use. It works like this:
MyClass.m file should look like this
#import "MyClass.h"
@implementation MyClass
- (void) myMethodToDoStuff {
//this will post a notification with myClassData (NSArray in this case) in its userInfo dict and self as an object
[[NSNotificationCenter defaultCenter] postNotificationName:@"myClassUpdatedData"
object:self
userInfo:[NSDictionary dictionaryWithObject:selectedLocation[@"myClassData"] forKey:@"myClassData"]];
}
@end
To use your notification in another classes: Add class as an observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherClassUpdatedItsData:) name:@"myClassUpdatedData" object:nil];
Implement the selector:
- (void) otherClassUpdatedItsData:(NSNotification *)note {
NSLog(@"*** Other class updated its data ***");
MyClass *otherClass = [note object]; //the object itself, you can call back any selector if you want
NSArray *otherClassData = [note userInfo][@"myClassData"]; //get myClass data object and do whatever you want with it
}
Don't forget to remove your class as an observer if
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>teste4</groupId>
<artifactId>teste4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bootstrap</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.Final</version>
</dependency>
</dependencies>
</project>
http://www.youtube.com/watch?v=zLZhSSXAwxI
Just watched this video and came out with implementation. It looks easy for me to understand. Please critique this.
visited_node={root}
stack.push(root)
while(!stack.empty){
unvisited_node = get_unvisited_adj_nodes(stack.top());
If (unvisited_node!=null){
stack.push(unvisited_node);
visited_node+=unvisited_node;
}
else
stack.pop()
}
Try the following commands in terminal, this will work better:
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html
To tweak a bit in order to handle the case where the variable is not set you could use a default value:
@Value("${spring.profiles.active:unknown}")
private String activeProfile;
This way if spring.profiles.active
is set, it will take it else it will take the default value unknown
.
So no exception will be triggered. And no need to force add something like @ActiveProfiles("test")
in your test to make it pass.
Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
function findKey(object, value) {
for (let key in object)
if (object[key] === value) return key;
return "key is not found";
}
const object = { id_1: "apple", id_2: "pear", id_3: "peach" };
console.log(findKey(object, "pear"));
//expected output: id_2
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.
vi my_celery_apps/app1.py
app = Celery(worker_name)
vi tasks/task1.py
from my_celery_apps.app1 import app
app.AsyncResult(taskid)
try:
if task.state.lower() != "success":
return
except:
""" do something """
Given that the remote repository has been cached via git fetch
it should be possible to compare against these commits. Try the following:
$ git fetch origin
$ git diff origin/master
According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp
The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.
This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.
Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):
HTML:
<footer>
<p><a href="page">Footer Link</a></p>
<p>© 2014 Company</p>
</footer>
CSS:
footer {
background:url(/img/headerbg.png) repeat-x 0 0;
/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}
/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}
So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.
I rely on NDEBUG
, because it's the only one whose behavior is standardized across compilers and implementations (see documentation for the standard assert macro). The negative logic is a small readability speedbump, but it's a common idiom you can quickly adapt to.
To rely on something like _DEBUG
would be to rely on an implementation detail of a particular compiler and library implementation. Other compilers may or may not choose the same convention.
The third option is to define your own macro for your project, which is quite reasonable. Having your own macro gives you portability across implementations and it allows you to enable or disable your debugging code independently of the assertions. Though, in general, I advise against having different classes of debugging information that are enabled at compile time, as it causes an increase in the number of configurations you have to build (and test) for arguably small benefit.
With any of these options, if you use third party code as part of your project, you'll have to be aware of which convention it uses.
await setTimeout(()=>{}, 200);
Will work if your Node version is 15 and above.
Used the answer above, but altered it for my needs.
I used the following function and imported to my REACT file where I needed to download the csv file.
I had a span
tag within my th
elements. Added comments to what most functions/methods do.
import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';
export function tableToCSV(){
let tableHeaders = Array.from(document.querySelectorAll('th'))
.map(item => {
// title = splits elem tags on '\n',
// then filter out blank "" that appears in array.
// ex ["Timestamp", "[Full time]", ""]
let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
return title
}).join(",")
const rows = Array.from(document.querySelectorAll('tr'))
.reduce((arr, currRow) => {
// if tr tag contains th tag.
// if null return array.
if (currRow.querySelector('th')) return arr
// concats individual cells into csv format row.
const cells = Array.from(currRow.querySelectorAll('td'))
.map(item => item.innerText)
.join(',')
return arr.concat([cells])
}, [])
return tableHeaders + '\n' + rows.join('\n')
}
export function downloadCSV(csv){
const csvFile = new Blob([csv], { type: 'text/csv' })
const downloadLink = document.createElement('a')
// sets the name for the download file
downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
// sets the url to the window URL created from csv file above
downloadLink.href = window.URL.createObjectURL(csvFile)
// creates link, but does not display it.
downloadLink.style.display = 'none'
// add link to body so click function below works
document.body.appendChild(downloadLink)
downloadLink.click()
}
When user click export to csv it trigger the following function in react.
handleExport = (e) => {
e.preventDefault();
const csv = tableToCSV()
return downloadCSV(csv)
}
Example html table elems.
<table id="datatable">
<tbody>
<tr id="tableHeader" className="t-header">
<th>Timestamp
<span className="block">full time</span></th>
<th>current rate
<span className="block">alt view</span>
</th>
<th>Battery Voltage
<span className="block">current voltage
</span>
</th>
<th>Temperature 1
<span className="block">[C]</span>
</th>
<th>Temperature 2
<span className="block">[C]</span>
</th>
<th>Time & Date </th>
</tr>
</tbody>
<tbody>
{this.renderData()}
</tbody>
</table>
</div>
Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.
However, you can convert strings to numbers like this:
pd.Series(['123', '42']).astype(float)
instead of float(series)
Try this: edited
@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause
Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.
update Original
set Original.Vaal= t.vaal
from Original join (select * from staging1 union select * from staging2) t
on Original.id=t.id
using (var client = new HttpClient(handler))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
This worked for me
Another way if you must use cut command
ps axu | grep [j]boss |awk '$1=$1'|cut -d' ' -f5
In Solaris, replace awk with nawk
or /usr/xpg4/bin/awk
Neither is better than the other, they do exactly the same thing. However, using .encode()
and .decode()
is the more common way to do it. It is also compatible with Python 2.
Can you execute the following code below. It worked in Oracle.
SELECT COUNT(COUNT(*))
FROM temptable
GROUP BY column_1, column_2, column_3, column_4
Arrow functions => best ES6 feature so far. They are a tremendously powerful addition to ES6, that I use constantly.
Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this
where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.
But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.
They do not have this
It uses “lexical scoping” to figure out what the value of “this
”
should be. In simple word lexical scoping it uses “this
” from the
inside the function’s body.
They do not have arguments
Arrow functions don’t have an arguments
object. But the same
functionality can be achieved using rest parameters.
let sum = (...args) => args.reduce((x, y) => x + y, 0)
sum(3, 3, 1) // output - 7
`
They cannot be used with new
Arrow functions can't be construtors because they do not have a prototype property.
map
, reduce
, or forEach
.I also had the same issue, I solved the problem by adding a ng-submit which sets the variable submitted to true.
<form name="form" ng-submit="submitted = true" novalidate>
<div>
<span ng-if="submitted && form.email.$error.email">invalid email address</span>
<span ng-if="submitted && form.email.$error.required">required</span>
<label>email</label>
<input type="email" name="email" ng-model="user.email" required>
</div>
<div>
<span ng-if="submitted && form.name.$error.required">required</span>
<label>name</label>
<input type="text" name="name" ng-model="user.name" required>
</div>
<button ng-click="form.$valid && save(user)">Save</button>
</form>
I like the idea of using $submitted, I think I've to upgrade Angular to 1.3 ;)
to set Oracle's Java SE Development Kit as the system default Java just download the latest Java SE Development Kit from here then create a directory somewhere you like in your file system for example /usr/java
now extract the files you just downloaded in that directory:
$ sudo tar xvzf jdk-8u5-linux-i586.tar.gz -C /usr/java
now to set your JAVA_HOME
environment variable:
$ JAVA_HOME=/usr/java/jdk1.8.0_05/
$ sudo update-alternatives --install /usr/bin/java java ${JAVA_HOME%*/}/bin/java 20000
$ sudo update-alternatives --install /usr/bin/javac javac ${JAVA_HOME%*/}/bin/javac 20000
make sure the Oracle's java is set as default java by:
$ update-alternatives --config java
you get something like this:
There are 2 choices for the alternative java (providing /usr/bin/java).
Selection Path Priority Status
------------------------------------------------------------
* 0 /opt/java/jdk1.8.0_05/bin/java 20000 auto mode
1 /opt/java/jdk1.8.0_05/bin/java 20000 manual mode
2 /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java 1061 manual mode
Press enter to keep the current choice[*], or type selection number:
pay attention to the asterisk before the numbers on the left and if the correct one is not set choose the correct one by typing the number of it and pressing enter. now test your java:
$ java -version
if you get something like the following, you are good to go:
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) Server VM (build 25.5-b02, mixed mode)
also note that you might need root permission or be in sudoers group to be able to do this. I've tested this solution on both ubuntu 12.04 and Debian wheezy and it works in both of them.
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
var x = from t in types
group t by t.Type into grouped
select new { type = grouped.Key,
count = grouped.Count() };
# practices 2
str = "Amin Is A Good Programmer"
new_set = str.replace('Good', '')
print(new_set)
print : Amin Is A Programmer
Dll not found. Install Visual C++ 2015 redistributable to fix.
mcilist = (from mci in mcilist select mci).Distinct().ToList();
In case you want to remove timestamps from existing model, as mentioned before, place this in your Model:
public $timestamps = false;
Also create a migration with following code in the up()
method and run it:
Schema::table('your_model_table', function (Blueprint $table) {
$table->dropTimestamps();
});
You can use $table->timestamps()
in your down()
method to allow rolling back.
"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"
The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53
Note that -an defines that audio should be skipped.
var SendInfo= { SendInfo: [... your elements ...]};
$.ajax({
type: 'post',
url: 'Your-URI',
data: JSON.stringify(SendInfo),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
...
}
});
and in action
public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){
...
you can bind your array like this
var SendInfo = [];
$(this).parents('table').find('input:checked').each(function () {
var domain = {
name: $("#id-manuf-name").val(),
address: $("#id-manuf-address").val(),
phone: $("#id-manuf-phone").val(),
}
SendInfo.push(domain);
});
hope this can help you.
In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).
Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".
Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.
The derivedFactor
function from mosaic
package seems to be designed to handle this. Using this example, it would look like:
library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
"2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
"3" = (a == 0 | a == 1 | a == 4 | a == 3 | c == 4),
.method = "first",
.default = NA
))
(If you want the result to be numeric instead of a factor, you can wrap derivedFactor
in an as.numeric
call.)
derivedFactor
can be used for an arbitrary number of conditionals, too.
At a very high level:
Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.
CREATE OR REPLACE function f_add_col(_tbl regclass, _col text, _type regtype)
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = _tbl
AND attname = _col
AND NOT attisdropped) THEN
RETURN FALSE;
ELSE
EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
RETURN TRUE;
END IF;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT f_add_col('public.kat', 'pfad1', 'int');
Returns TRUE
on success, else FALSE
(column already exists).
Raises an exception for invalid table or type name.
This could be done with a DO
statement, but DO
statements cannot return anything. And if it's for repeated use, I would create a function.
I use the object identifier types regclass
and regtype
for _tbl
and _type
which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col
has still to be sanitized for EXECUTE
with quote_ident()
. More explanation in this related answer:
format()
requires Postgres 9.1+. For older versions concatenate manually:
EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
You can schema-qualify your table name, but you don't have to.
You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).
I query pg_catalog
instead of the information_schema
. Detailed explanation:
Blocks containing an EXCEPTION
clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:
Tip: A block containing an
EXCEPTION
clause is significantly more expensive to enter and exit than a block without one. Therefore, don't useEXCEPTION
without need.
I know this is an old question but I want to share an example that I think explains bounded wildcards pretty well. java.util.Collections
offers this method:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
If we have a List of T
, the List can, of course, contain instances of types that extend T
. If the List contains Animals, the List can contain both Dogs and Cats (both Animals). Dogs have a property "woofVolume" and Cats have a property "meowVolume." While we might like to sort based upon these properties particular to subclasses of T
, how can we expect this method to do that? A limitation of Comparator is that it can compare only two things of only one type (T
). So, requiring simply a Comparator<T>
would make this method usable. But, the creator of this method recognized that if something is a T
, then it is also an instance of the superclasses of T
. Therefore, he allows us to use a Comparator of T
or any superclass of T
, i.e. ? super T
.
Currently i am using since this is trustable for getting location and calculating distance for my application...... i am using this for my taxi application.
use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately. for detail get to link https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long ONE_MIN = 500;
private static final long TWO_MIN = 500;
private static final long FIVE_MIN = 500;
private static final long POLLING_FREQ = 1000 * 20;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 1.0f;
private static final float MIN_LAST_READ_ACCURACY = 1;
private LocationRequest mLocationRequest;
private Location mBestReading;
TextView tv;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!servicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onPause() {d
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
tv.setText(location + "");
// Determine whether new location is better than current best
// estimate
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
mBestReading = location;
if (mBestReading.getAccuracy() < MIN_ACCURACY) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
@Override
public void onConnected(Bundle dataBundle) {
// Get first reading. Get additional location updates if necessary
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//Schedule a runnable to unregister location listeners
@Override
public void run() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
}, ONE_MIN, TimeUnit.MILLISECONDS);
}
}
}
@Override
public void onConnectionSuspended(int i) {
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//tv.setText(mCurrentLocation+"");
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
}
else {
return bestResult;
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
return false;
}
}
}
An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:
LowerLimit UpperLimit Range
0 9 '0-9'
10 19 '10-19'
20 29 '20-29'
30 39 '30-39'
And a query that looks like this:
Select
Range as [Score Range],
Count(*) as [Number of Occurences]
from
Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
group by Range
This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!
datamap = eval(input('Provide some data here: '))
means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval
.
ast.literal_eval
raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
Use ast.literal_eval
whenever you need eval
. You shouldn't usually evaluate literal Python statements.
Because Vue props is one way data flow, This prevents child components from accidentally mutating the parent’s state.
From the official Vue document, we will find 2 ways to solve this problems
if child component want use props as local data, it is best to define a local data property.
props: ['list'],
data: function() {
return {
localList: JSON.parse(this.list);
}
}
The prop is passed in as a raw value that needs to be transformed. In this case, it’s best to define a computed property using the prop’s value:
props: ['list'],
computed: {
localList: function() {
return JSON.parse(this.list);
},
//eg: if you want to filter this list
validList: function() {
return this.list.filter(product => product.isValid === true)
}
//...whatever to transform the list
}
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.
When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
look at this: https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode. keyCode is always set in the keydown and keyup events. In these cases, charCode is never set. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters entered through an IME do not register through keyCode or charCode.
if you are using login page in your website go to web.config file
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="index.aspx" >
</forms>
</authentication>
replace your authentication tag to above (where index.aspx will be your startup page)
and one more thing write this in your web.config file inside
<configuration>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
</files>
</defaultDocument>
</system.webServer>
<location path="index.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
</configuration>
Just use xcopy /y source destination
The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.
A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.
Example, Dockerfile
FROM ubuntu:latest
MAINTAINER john doe
RUN apt-get update
RUN apt-get install -y python python-pip wget
RUN pip install Flask
ADD hello.py /home/hello.py
WORKDIR /home
Docker Compose
is a tool for defining and running multi-container Docker applications.
define the services that make up your app in docker-compose.yml
so they can be run together in an isolated environment.
get an app running in one command by just running docker-compose up
Example, docker-compose.yml
version: "3"
services:
web:
build: .
ports:
- '5000:5000'
volumes:
- .:/code
- logvolume01:/var/log
links:
- redis
redis:
image: redis
volumes:
logvolume01: {}
Casting is only for C++ not C.In case you are using a C++ compiler you better change it to C compiler.
<?php
set_time_limit(0);
//This is the file where we save the information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Even more minimal example (draws "Hello world!" in black and with the default font in the top-left of the image):
...
from PIL import ImageDraw
...
ImageDraw.Draw(
image # Image
).text(
(0, 0), # Coordinates
'Hello world!', # Text
(0, 0, 0) # Color
)
If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates
.
Some details:
In my case I was trying to run examples of project flask_simple_ui and jinja
would always say
jinja2.exceptions.TemplateNotFound: form.html
The trick was that sample program would import installed package flask_simple_ui
. And ninja
being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui
, instead of os.getcwd()
as one would expect.
To my bad luck, setup.py
has a bug and doesn't copy any html files, including the missing form.html
. Once I fixed setup.py
, the problem with TemplateNotFound vanished.
I hope it helps someone.
Update 2015/06
As jQuery has evolved since the question was posted, the recommended approach now is using $.on
$(document).ready(function() {
$("input[name=group2]").on( "change", function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
} );
});
or outside $.ready()
$(document).on( "change", "input[name=group2]", function() { ... } );
Original answer
You should use .change()
event handler:
$(document).ready(function(){
$("input[name=group2]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
should work
You could subscribe to the TextChanged
event on the TextBox
and if the text is empty set the Button
to disabled. Or you could bind the Button.IsEnabled
property to the TextBox.Text
property and use a converter that returns true if there is any text and false otherwise.
Just an observation I just made while building naive code on OSX with cmake:
cmake ... -DBUILD_SHARED_LIBS=OFF ...
creates .so files
while
cmake ... -DBUILD_SHARED_LIBS=ON ...
creates .dynlib files.
Perhaps this helps anyone.
In a real world environment it's never a good idea to work solely with time
, always use datetime
, even better utc
, to avoid conflicts like overnight, daylight saving, different timezones between user and server etc.
So I'd recommend this approach:
import datetime as dt
_now = dt.datetime.now() # or dt.datetime.now(dt.timezone.utc)
_in_5_sec = _now + dt.timedelta(seconds=5)
# get '14:39:57':
_in_5_sec.strftime('%H:%M:%S')
For Linux/Mac only, export the installed Visual Studio Code extensions in the form of an installation script. It's a Z shell (Zsh) script, but it may run in Bash as well.
https://gist.github.com/jvlad/6c92178bbfd1906b7d83c69780ee4630
I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.
I solved it by using os.walk()
, recursively calling my function and using shutil.move()
on files which I wanted to overwrite and folders which did not exist.
It works like shutil.move()
, but with the benefit that existing files are only overwritten, but not deleted.
import os
import shutil
def moverecursively(source_folder, destination_folder):
basename = os.path.basename(source_folder)
dest_dir = os.path.join(destination_folder, basename)
if not os.path.exists(dest_dir):
shutil.move(source_folder, destination_folder)
else:
dst_path = os.path.join(destination_folder, basename)
for root, dirs, files in os.walk(source_folder):
for item in files:
src_path = os.path.join(root, item)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_path, dst_path)
for item in dirs:
src_path = os.path.join(root, item)
moverecursively(src_path, dst_path)
For form login:
<form method="post" action="/login">
<input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
<input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
<input type="submit" id="send" value="Send">
</form>
Javascript:
$(document).ready(function() {
$('#send').prop('disabled', true);
$('#email, #password').keyup(function(){
if ($('#password').val() != '' && $('#email').val() != '')
{
$('#send').prop('disabled', false);
}
else
{
$('#send').prop('disabled', true);
}
});
});
I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style
element to the document's head like:
$('head').append('<style>.column:before{width:800px !important;}</style>');
See a live demo here
I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
More powerful slug generation method on pure JavaScript. It's basically support transliteration for all Cyrillic characters and many Umlauts (German, Danish, France, Turkish, Ukrainian and etc.) but can be easily extended.
function makeSlug(str)_x000D_
{_x000D_
var from="? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? a a ä á à â å c c e e e é è ê æ g g ö ó ø ? ô o ? ? n ? r s ü ß r l d þ h ? i ï í î j k l n n n r š s t u ú û ? ù ü u u ý ÿ ž z z ç ? ?".split(' ');_x000D_
var to= "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' ');_x000D_
_x000D_
str = str.toLowerCase();_x000D_
_x000D_
// remove simple HTML tags_x000D_
str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, '');_x000D_
_x000D_
str = str.replace(/^\s+|\s+$/gm,''); // trim spaces_x000D_
_x000D_
for(i=0; i<from.length; ++i)_x000D_
str = str.split(from[i]).join(to[i]);_x000D_
_x000D_
// Replace different kind of spaces with dashes_x000D_
var spaces = [/( | | )/gi, /(—|–|‑)/gi,_x000D_
/[(_|=|\\|\,|\.|!)]+/gi, /\s/gi];_x000D_
_x000D_
for(i=0; i<from.length; ++i)_x000D_
str = str.replace(spaces[i], '-');_x000D_
str = str.replace(/-{2,}/g, "-");_x000D_
_x000D_
// remove special chars like &_x000D_
str = str.replace(/&[a-z]{2,7};/gi, '');_x000D_
str = str.replace(/&#[0-9]{1,6};/gi, '');_x000D_
str = str.replace(/&#x[0-9a-f]{1,6};/gi, '');_x000D_
_x000D_
str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff_x000D_
str = str.replace(/^\-+|\-+$/gm,''); // trim edges_x000D_
_x000D_
return str;_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> ‪???&???<strong>??_????</strong>?…???????????\r???\n?–?????? ??????\t \n?\t??????´? ??\\?????–????????\t????.Danke schön!ich heiße=?áÞÿá-Skånske,København çagatay rí gé tor zöldülésetekrol - . ");
_x000D_
<div>_x000D_
<pre>Hello world!</pre>_x000D_
</div>
_x000D_
This answer is excerpted from this article authored by Michael Kauffman.
Use Git for Windows with a corporate SSL certificate
Issue:
If you have a corporate SSL certificate and want to clone your repo from the console or VSCode you get the following error:
fatal: unable to access ‘https://myserver/tfs/DefaultCollection/_git/Proj/’: SSL certificate problem: unable to get local issuer certificate
Solution:
Export the root self-signed Certificate to a file. You can do this from within your browser.
Locate the “ca-bundle.crt” file in your git folder (current version C:\Program Files\Git\usr\ssl\certs but is has changed in the past). Copy the file to your user profile. Open it with a text editor like VSCode and add the content of your exported certificate to the end of the file.
Now we have to configure git to use the new file:
git config --global http.sslCAInfo C:/Users/<yourname>/ca-bundle.crt
This will add the following entry to your .gitconfig file in the root of your user profile.
[http]
sslCAInfo = C:/Users/<yourname>/ca-bundle.crt
As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody
is active by default, so all the Java objects are serialized to JSON representation in the response body.
As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:
git reset HEAD .
(note the trailing dot)git stash
git checkout master
git fetch upstream; git merge upstream/master
git checkout new-branch; git rebase master
git stash apply stash@{1}
In .htaccess file at site root directory edit following line:
<ifmodule mod_security.c>_x000D_
_x000D_
SecFilterEngine Off_x000D_
SecFilterScanPOST Off_x000D_
_x000D_
</ifmodule>_x000D_
_x000D_
<IfModule mod_rewrite.c>_x000D_
RewriteEngine On_x000D_
RewriteBase /_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
RewriteCond %{REQUEST_FILENAME} !-d_x000D_
RewriteRule . /index.php [L]_x000D_
</IfModule>
_x000D_
Just keep the mod_security rules like SecFilterEngine and parts apart from each other. Its works for apache server
In my case, I had already generated an APK file using the command ionic cordova build android --prod
and I needed to get the SHA-1 fingerprint for the already existing APK file. Here's how I got it by running the following command in the App directory:
keytool -list -printcert -jarfile app-debug.apk
So, I basically ran the above command in the following app location:
C:\myApp\platforms\android\app\build\outputs\apk\debug>keytool -list -printcert -jarfile app-debug.apk
This gave me the SHA1 fingerprint as: 7B:6B:AD:...
Hope this helps someone!
You can use TEXT
like this as part of a concatenation
=TEXT(A1,"dd-mmm-yy") & " other string"
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}
sudo apt-get install php-pear php7.x-dev
x is your php version like 7.2 the php7.2-dev
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
then add "extension=mcrypt.so" in "/etc/php/7.2/apache2/php.ini"
here php.ini is depends on your php installatio and apache used php version.
Try:
if (_checkbox.addEventListener) {
_checkbox.addEventListener("click", setCheckedValues, false);
}
else {
_checkbox.attachEvent("onclick", setCheckedValues);
}
Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
Old question I know, but this is now possible using the css property table-layout: fixed
on the table tag. Answer below from this question CSS percentage width and text-overflow in a table cell
This is easily done by using table-layout: fixed
, but a little tricky because not many people know about this CSS property.
table {
width: 100%;
table-layout: fixed;
}
See it in action at the updated fiddle here: http://jsfiddle.net/Fm5bM/4/
amount = list()
for col in df.columns:
val = list(df[col])
for v in val:
amount.append(v)
You can do something like this :
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />
Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a
is of dtype int32
, and the maximim value storable in an int32
is 2**31-1. Since 10**10 > 2**32-1
, the exponentiation results in a number that is bigger than that which can be stored in an int32
.
Note that you can not rely on np.seterr(all='warn')
to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes
so that no operation overflows.
Presumably from this site:
Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.
External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.
I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):
\begin{itemize}[leftmargin=0cm]
\item Foo
\item Bar
\end{itemize}
Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)
Try this:
$('#divID').css({"background":"none"});// remove existing
$('#divID').css({"background":"#bada55"});// add new color here.
Thanks
public class testCrop extends AppCompatActivity {
ImageView iv;
String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testcrpop);
iv = (ImageView) findViewById(R.id.testCrop);
imageDownload image = new imageDownload(testCrop.this, iv);
image.execute(imagePath);
}
class imageDownload extends AsyncTask<String, Integer, Bitmap> {
Context context;
ImageView imageView;
Bitmap bitmap;
InputStream in = null;
int responseCode = -1;
//constructor.
public imageDownload(Context context, ImageView imageView) {
this.context = context;
this.imageView = imageView;
}
@Override
protected void onPreExecute() {
}
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap data) {
imageView.setImageBitmap(data);
saveImage(data);
}
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
createFolder.mkdir();
File saveImage = new File(createFolder,"downloadimage.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Make sure you added permission to write data in memory
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
According to SolrQuerySyntax, you can use q=-id:[* TO *]
.
string
is a reference type, a class. You can only use Nullable<T>
or the T?
C# syntactic sugar with non-nullable value types such as int
and Guid
.
In particular, as string
is a reference type, an expression of type string
can already be null:
string lookMaNoText = null;
Here's how I get it to beep using HTML5: First I copy and convert the windows wav file to mp3, then I use this code:
var _beep = window.Audio("Content/Custom/Beep.mp3")
function playBeep() { _beep.play()};
It's faster to declare the sound file globally and refer to it as needed.
The man pages is the best source of information you can find... and is at your fingertips: man mkdir
yields this about -p
switch:
-p, --parents
no error if existing, make parent directories as needed
Use case example: Assume I want to create directories hello/goodbye
but none exist:
$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$
-p
created both, hello
and goodbye
This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.
About rlidwka
, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html
Directory permissions
l (lookup)
Allows one to list the contents of a directory. It does not allow the reading of files.
i (insert)
Allows one to create new files in a directory or copy new files to a directory.
d (delete)
Allows one to remove files and sub-directories from a directory.
a (administer)
Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory.
File permissions
r (read)
Allows one to read the contents of file in the directory.
w (write)
Allows one to modify the contents of files in a directory and use chmod on them.
k (lock)
Allows programs to lock files in a directory.
Hence rlidwka
means: All permissions on.
It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka
concept doesn't apply here.
$ git push -d <remote_name> <branch_name>
$ git branch -d <branch_name>
Note that in most cases the remote name is origin
.
In such a case you'll have to use the command like so.
$ git push -d origin <branch_name>
To delete the local branch use one of the following:
$ git branch -d branch_name
$ git branch -D branch_name
Note: The -d
option is an alias for --delete
, which only deletes the branch if it has already been fully merged in its upstream branch. You could also use -D
, which is an alias for --delete --force
, which deletes the branch "irrespective of its merged status." [Source: man git-branch
]
Also note that git branch -d branch_name
will fail if you are currently
in the branch you want to remove. The message starts with
error: Cannot delete the branch 'branch_name'
. If so, first switch
to some other branch, for example: git checkout master
.
As of Git v1.7.0, you can delete a remote branch using
$ git push <remote_name> --delete <branch_name>
which might be easier to remember than
$ git push <remote_name> :<branch_name>
which was added in Git v1.5.0 "to delete a remote branch or a tag."
Starting on Git v2.8.0 you can also use git push
with the -d
option as an alias for --delete
.
Therefore, the version of Git you have installed will dictate whether you need to use the easier or harder syntax.
From Chapter 3 of Pro Git by Scott Chacon:
Deleting Remote Branches
Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s master branch (or whatever branch your stable code-line is in). You can delete a remote branch using the rather obtuse syntax
git push [remotename] :[branch]
. If you want to delete your server-fix branch from the server, you run the following:
$ git push origin :serverfix
To [email protected]:schacon/simplegit.git
- [deleted] serverfix
Boom. No more branches on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the
git push [remotename] [localbranch]:[remotebranch]
syntax that we went over a bit earlier. If you leave off the[localbranch]
portion, then you’re basically saying, “Take nothing on my side and make it be[remotebranch]
.”
I issued git push origin: bugfix
and it worked beautifully. Scott Chacon was right—I will want to dog ear that page (or virtually dog ear by answering this on Stack Overflow).
Then you should execute this on other machines
# Fetch changes from all remotes and locally delete
# remote deleted branches/tags etc
# --prune will do the job :-;
git fetch --all --prune
to propagate changes.
I have found it best to add viewBox
and preserveAspectRatio
attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h
:
<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>
Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:
FROM ubuntu
COPY . /
RUN ls -la /
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
Many websites uses Django or Zope/Plone web framework, these are written in Python.
Python is used a lot for writing system administration software, usually when bash scripts (shell script) isn't up to the job, but going C/C++ is an overkill. This is also the spectrum where perl, awk, etc stands. Gentoo's emerge/portage is one example. Mercurial/HG is a distributed version control system (DVCS) written in python.
Many desktop applications are also written in Python. The original Bittorrent was written in python.
Python is also used as the scripting languages for GIMP, Inkscape, Blender, OpenOffice, etc. Python allows advanced users to write plugins and access advanced functionalities that cannot typically be used through a GUI.
No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.
I came across a similar problem. Had to sort a list of 3rd party class (objects).
List<ThirdPartyClass> tpc = getTpcList(...);
ThirdPartyClass does not implement the Java Comparable interface. I found an excellent illustration from mkyong on how to approach this problem. I had to use the Comparator approach to sorting.
//Sort ThirdPartyClass based on the value of some attribute/function
Collections.sort(tpc, Compare3rdPartyObjects.tpcComp);
where the Comparator is:
public abstract class Compare3rdPartyObjects {
public static Comparator<ThirdPartyClass> tpcComp = new Comparator<ThirdPartyClass>() {
public int compare(ThirdPartyClass tpc1, ThirdPartyClass tpc2) {
Integer tpc1Offset = compareUsing(tpc1);
Integer tpc2Offset = compareUsing(tpc2);
//ascending order
return tpc1Offset.compareTo(tpc2Offset);
}
};
//Fetch the attribute value that you would like to use to compare the ThirdPartyClass instances
public static Integer compareUsing(ThirdPartyClass tpc) {
Integer value = tpc.getValueUsingSomeFunction();
return value;
}
}
Did you recently updated your eclipse android plugin (adt r17)? Then the following link might help:
How to fix the classdefnotfounderror with adt-17
Update: One year has passed since the question arose. I will keep the link, because even in 2013 it seem to help some people to solve the problem. But please take care what you are doing, see Erics comment below. Current ADT-Version is 22, I recommend using the most current version.
You'll need to open the workbook to refer to it.
Sub Setwbk()
Dim wbk As Workbook
Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
Master Benchmark Data Sheet.xlsx")
End Sub
* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:
Why do I have to "set" it?
Set
is how VBA assigns object variables. Since a Range
and a Workbook
/Worksheet
are objects, you must use Set
with these.
You can examine the response object and verify that it contains the expected value:
@expected = {
:flashcard => @flashcard,
:lesson => @lesson,
:success => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected
EDIT
Changing this to a post
makes it a bit trickier. Here's a way to handle it:
it "responds with JSON" do
my_model = stub_model(MyModel,:save=>true)
MyModel.stub(:new).with({'these' => 'params'}) { my_model }
post :create, :my_model => {'these' => 'params'}, :format => :json
response.body.should == my_model.to_json
end
Note that mock_model
will not respond to to_json
, so either stub_model
or a real model instance is needed.
Use:
SELECT x.*
FROM (SELECT fname
FROM MyTbl) x
WHERE ROWNUM = 1
If using Oracle9i+, you could look at using analytic functions like ROW_NUMBER() but they won't perform as well as ROWNUM.
cd
to the repository then
find . -name ".git*" -exec rm -R {} \;
Make sure not to accidentally pipe a single dot, slash, asterisk, or other regex wildcard into find, or else rm
will happily delete it.
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
For me the issue was in Resharper License. It has been delinked from my account for some reason and it said that the license is invalid. When I linked it again to my JetBrains account it started to work properly after a few minutes.
I'm doing it with no additional tool. I have just added the following files to my Win32 app project.
One header file which defines some constants than we can reuse on our resource file and even on the program code. We only need to maintain one file. Thanks to the Qt team that showed me how to do it on a Qt project, it now also works on my Win32 app.
----[version.h]----
#ifndef VERSION_H
#define VERSION_H
#define VER_FILEVERSION 0,3,0,0
#define VER_FILEVERSION_STR "0.3.0.0\0"
#define VER_PRODUCTVERSION 0,3,0,0
#define VER_PRODUCTVERSION_STR "0.3.0.0\0"
#define VER_COMPANYNAME_STR "IPanera"
#define VER_FILEDESCRIPTION_STR "Localiza archivos duplicados"
#define VER_INTERNALNAME_STR "MyProject"
#define VER_LEGALCOPYRIGHT_STR "Copyright 2016 [email protected]"
#define VER_LEGALTRADEMARKS1_STR "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR "MyProject.exe"
#define VER_PRODUCTNAME_STR "My project"
#define VER_COMPANYDOMAIN_STR "www.myurl.com"
#endif // VERSION_H
----[MyProjectVersion.rc]----
#include <windows.h>
#include "version.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4"
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR
VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR
VALUE "OriginalFilename", VER_ORIGINALFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
Well there is no direct method to do it You can consider some workarounds.
If you dont need a definite border (clearcut border) then you can depend on shadow for the purpose
[view1 setBackgroundColor:[UIColor blackColor]];
UIColor *color = [UIColor yellowColor];
view1.layer.shadowColor = [color CGColor];
view1.layer.shadowRadius = 10.0f;
view1.layer.shadowOpacity = 1;
view1.layer.shadowOffset = CGSizeZero;
view1.layer.masksToBounds = NO;
In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
popuMenu.inflate(R.menu.bottom_nav_menu);
popuMenu.show();
}
},100);
It looks like there is no difference, for
uses each
underneath.
$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
from (irb):4
Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment
for .. in ..
sets the iterator outside the scope of the loop, so
for a in [1,2]
puts a
end
leaves a
defined after the loop is finished. Where as each
doesn't. Which is another reason in favor of using each
, because the temp variable lives a shorter period.
Have you considered using Javascript for this?
$('input').val($('input').val().replace(',', '.'));
String mystring = new String(mychararray);
Sure, being in master
branch all you need to do is:
git merge <commit-id>
where commit-id
is hash of the last commit from newbranch
that you want to get in your master
branch.
You can find out more about any git command by doing git help <command>
. It that case it's git help merge
. And docs are saying that the last argument for merge
command is <commit>...
, so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.
The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.
Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:
//gradle.build snippet
allprojects {
...
repositories {
//All sub-projects will now refer to the same 'libs' directory
flatDir {
dirs "$rootProject.projectDir/libs"
}
mavenCentral()
}
...
}
EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).
isset('user.permissions.saveProject', args);
function isset(string, context) {
try {
var arr = string.split('.');
var checkObj = context || window;
for (var i in arr) {
if (checkObj[arr[i]] === undefined) return false;
checkObj = checkObj[arr[i]];
}
return true;
} catch (e) {
return false;
}
}
The shortest answer is
Please try this.
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
This worked for me..
select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view
I like Roy Osherove's naming strategy. It's the following:
[UnitOfWork_StateUnderTest_ExpectedBehavior]
It has every information needed on the method name and in a structured manner.
The unit of work can be as small as a single method, a class, or as large as multiple classes. It should represent all the things that are to be tested in this test case and are under control.
For assemblies, I use the typical .Tests
ending, which I think is quite widespread and the same for classes (ending with Tests
):
[NameOfTheClassUnderTestTests]
Previously, I used Fixture as suffix instead of Tests, but I think the latter is more common, then I changed the naming strategy.
If your form is PHP based, it would work this way within your " <?php $data = array(" code:
'onkeypress' => 'return /[a-z 0-9]/i.test(event.key)',
SHORTEST and FASTEST: str.replace(/ /g, '');
Benchmark:
Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):
Short string similar to examples from OP question
The fastest solution on all browsers is / /g
(regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join
solution. Change
to \s
or add +
or i
to regexp slows down processing.
For string about ~3 milion character results are:
You can run it on your machine: https://jsperf.com/remove-string-spaces/1
I hit the same problem with "Visual Studio 2013".
LNK1104: cannot open file 'debug\****.exe
It resolved after closing and re-starting Visual studio.
In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.
Shims can be found here: MDN Array.filter or ES5-shim
var result = restaurants.filter(function (chain) {
return chain.restaurant.food === "chicken";
})[0].restaurant.name;
I only know a way around this. The idea is to export that list of pdf files you have into a file. Then split that file into several parts. Then remove pdf files listed in each part.
ls | grep .pdf > list.txt
wc -l list.txt
wc -l is to count how many line the list.txt contains. When you have the idea of how long it is, you can decide to split it in half, forth or something. Using split -l command For example, split it in 600 lines each.
split -l 600 list.txt
this will create a few file named xaa,xab,xac and so on depends on how you split it. Now to "import" each list in those file into command rm, use this:
rm $(<xaa)
rm $(<xab)
rm $(<xac)
Sorry for my bad english.
use ONLY
function init() {
about = document.getElementById("about");
about.style.color = 'blue';
}
.innerHTML()
sets or gets the HTML syntax describing the element's descendants., All you need is an object here.
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
Now a day use of gravity start
is best choise:
android:gravity="start"
For EditText (textarea):
<EditText
android:id="@+id/EditText02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="start"
android:inputType="textMultiLine"
/>
There is another case where 'Java Class' don't show, maybe some reserved words exist in the package name, for example:
com.liuyong.package.case
com.liuyong.import.package
It's the same reason as @kuporific 's answer: the package name is invalid.
I read a lot of answers but none seems to correctly explain where the word double comes from. I remember a very good explanation given by a University professor I had some years ago.
Recalling the style of VonC's answer, a single precision floating point representation uses a word of 32 bit.
Representation:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
bits: 31 30 23 22 0
(Just to point out, the sign bit is the last, not the first.)
A double precision floating point representation uses a word of 64 bit.
Representation:
S EEEEEEEEEEE MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
bits: 63 62 52 51 0
As you may notice, I wrote that the mantissa has, in both types, one bit more of information compared to its representation. In fact, the mantissa is a number represented without all its non-significative 0
. For example,
This means that the mantissa will always be in the form
0.a1a2...at × ßp
where ß is the base of representation. But since the fraction is a binary number, a1 will always be equal to 1, thus the fraction can be rewritten as 1.a2a3...at+1 × 2p and the initial 1 can be implicitly assumed, making room for an extra bit (at+1).
Now, it's obviously true that the double of 32 is 64, but that's not where the word comes from.
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
With that said, it's easy to estimate the number of decimal digits which can be safely used:
I use EditText.setFocusable(false)
and set true again if I want to edit.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M
Use all 3 in .htaccess
after everything at last line. php_value post_max_size
must be more than than the remaining two.
What about using checkout command :
git diff --stat "$branch"
git checkout --merge "$branch" "$file"
git diff --stat "$branch"
I am using Linux and have nvm
and working with more than 7 version of node
As of my experience I experienced the same situation with my latest project (actually not hours but minutes as I can't wait hours because of hourly project :))
Disclaimer: don't try below option until you know how cache clean works
npm cache clean --force
and then all working fine for me so it's looks like sometimes npm's cache gets confused with different versions of Node.
Official documentation of Npm cache can be found here
Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('<a/>')
.addClass('ui-all')
.text(countries[i])
.appendTo(li);
});