What worked for me was setting aspnet:MaxHttpCollectionKeys to a high value on appSettings tag on the inetpub VirtualDirectories\443\web.config file:
<configuration>
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="100000" />
</appSettings>
</configuration>
For those using the internal IIS of Visual Studio, try the following:
I hope this helps someone out there!
I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.
I got this error when I dynamically read data from a WebRequest
and never closed the Response
.
protected System.IO.Stream GetStream(string url)
{
try
{
System.IO.Stream stream = null;
var request = System.Net.WebRequest.Create(url);
var response = request.GetResponse();
if (response != null) {
stream = response.GetResponseStream();
// I never closed the response thus resulting in the error
response.Close();
}
response = null;
request = null;
return stream;
}
catch (Exception) { }
return null;
}
On windows 10 (client) you can also script this using
Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName WCF-HTTP-Activation45 -All
Note that this is a different command from the server skus
Better code with adding a subclass AuthorizeRole.cs
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params Rolenames[] roles)
{
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Unauthorized" },
{ "controller", "Home" },
{ "area", "" }
}
);
//base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Login" },
{ "controller", "Account" },
{ "area", "" },
{ "returnUrl", HttpContext.Current.Request.Url }
}
);
}
}
}
How to use this
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
public ActionResult Index()
{
return View();
}
You can use the for command:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Type
for /?
at the command prompt. Also, you can parse ini files!
Solved this by doing a few things, first getting the height
of my TextView
and diving it by the text size
to get the total amount of lines possible with the TextView
.
int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize();
After you get this value you need to set your TextView
maxLines
to this new value.
TextView.setMaxLines(maxLines);
Set the Gravity
to Bottom
once the maximum amount of lines has been exceeded and it will scroll down automatically.
if (TextView.getLineCount() >= maxLines) {
TextView.setGravity(Gravity.BOTTOM);
}
In order for this to work correctly, you must use append()
to the TextView
, If you setText()
this will not work.
TextView.append("Your Text");
The benefit of this method is that this can be used dynamically regardless of the height
of your TextView
and the text size
. If you decide to make modifications to your layout this code would still work.
The get_all_related_fields()
method mentioned herein has been deprecated in 1.8. From now on it's get_fields()
.
>> from django.contrib.auth.models import User
>> User._meta.get_fields()
Also if you want to do something like ClassB.Run("thing");
, make sure the Method Run();
is static
or you could call it like this: thing.Run("thing");
.
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready" For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
Try this dude,
<button onclick="goBack()">Go Back 2 Pages</button>
<script>
function goBack() {
window.history.go(-2);
}
</script>
So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>
.
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
Additionally, it is often required to add the following to web.config
in the handlers. Thanks to Babak
<handlers>
<remove name="WebDAV" />
...
</handlers>
You can also do it with pure python without using any modules.
# format as a block of csv text to do whatever you want
csv_rows = ["{},{}".format(i, j) for i, j in array]
csv_text = "\n".join(csv_rows)
# write it to a file
with open('file.csv', 'w') as f:
f.write(csv_text)
Login your Google account at myaccount.google.com/security go to "Login" and then "Security", scroll to bottom then enable the "Allow less secure apps" option.
This worked for me:
$('#SelectListId').prepend('<option selected></option>').select2({
placeholder: "Select Month",
allowClear: true
});
Hope this help :)
the Jquery append function returns a jQuery object so you can just tag a method on the end
$("#root").append(child).anotherJqueryMethod();
If what you're saying is that you want to get all inputs inside a form that have a value without worrying about the input type, try this:
Example: http://jsfiddle.net/nfLfa/
var $inputs = $('form').find(':checked,:selected,:text,textarea').filter(function() {
return $.trim( this.value ) != '';
});
Now you should have a set of input elements that have some value.
You can put the values in an array:
var array = $inputs.map(function(){
return this.value;
}).get();
Or you could serialize them:
var serialized = $inputs.serialize();
Chrome wants to focus on a control that is required but still empty so that it can pop up the message 'Please fill out this field'. However, if the control is hidden at the point that Chrome wants to pop up the message, that is at the time of form submission, Chrome can't focus on the control because it is hidden, therefore the form won't submit.
So, to get around the problem, when a control is hidden by javascript, we also must remove the 'required' attribute from that control.
Just because I think the other answers pretty much go off on a tangent of whether a football team "is-a" List<FootballPlayer>
or "has-a" List<FootballPlayer>
, which really doesn't answer this question as written.
The OP chiefly asks for clarification on guidelines for inheriting from List<T>
:
A guideline says that you shouldn't inherit from
List<T>
. Why not?
Because List<T>
has no virtual methods. This is less of a problem in your own code, since you can usually switch out the implementation with relatively little pain - but can be a much bigger deal in a public API.
What is a public API and why should I care?
A public API is an interface you expose to 3rd party programmers. Think framework code. And recall that the guidelines being referenced are the ".NET Framework Design Guidelines" and not the ".NET Application Design Guidelines". There is a difference, and - generally speaking - public API design is a lot more strict.
If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?
Pretty much, yeah. You may want to consider the rationale behind it to see if it applies to your situation anyway, but if you're not building a public API then you don't particularly need to worry about API concerns like versioning (of which, this is a subset).
If you add a public API in the future, you will either need to abstract out your API from your implementation (by not exposing your List<T>
directly) or violate the guidelines with the possible future pain that entails.
Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?
Depends on the context, but since we're using FootballTeam
as an example - imagine that you can't add a FootballPlayer
if it would cause the team to go over the salary cap. A possible way of adding that would be something like:
class FootballTeam : List<FootballPlayer> {
override void Add(FootballPlayer player) {
if (this.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
}
Ah...but you can't override Add
because it's not virtual
(for performance reasons).
If you're in an application (which, basically, means that you and all of your callers are compiled together) then you can now change to using IList<T>
and fix up any compile errors:
class FootballTeam : IList<FootballPlayer> {
private List<FootballPlayer> Players { get; set; }
override void Add(FootballPlayer player) {
if (this.Players.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
/* boiler plate for rest of IList */
}
but, if you've publically exposed to a 3rd party you just made a breaking change that will cause compile and/or runtime errors.
TL;DR - the guidelines are for public APIs. For private APIs, do what you want.
This works on any random unknown width of the absolute positioned element you want to have in the centre of your container element:
<div class="container">
<div class="box">
<img src="https://picsum.photos/200/300/?random" alt="">
</div>
</div>
.container {
position: relative;
width: 100%;
}
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
You can add
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
to your application.properties
file.
You shouldn't use a space " " instead of "0" because the excel deal with the space as a value.
So, the answer is with the option by (Ctrl + F). Then, click the options and put in the Find with "0". Next, click (Match entire cell contents. Finally, replaced or replaced all up to you.
This solution can give more also. You can use (*) before or after the values to delete any parts you want.
Thanks.
The IEnumerable and IEnumerator Interfaces
To begin examining the process of implementing existing .NET interfaces, let’s first look at the role of IEnumerable and IEnumerator. Recall that C# supports a keyword named foreach that allows you to iterate over the contents of any array type:
// Iterate over an array of items.
int[] myArrayOfInts = {10, 20, 30, 40};
foreach(int i in myArrayOfInts)
{
Console.WriteLine(i);
}
While it might seem that only array types can make use of this construct, the truth of the matter is any type supporting a method named GetEnumerator() can be evaluated by the foreach construct.To illustrate, follow me!
Suppose we have a Garage class:
// Garage contains a set of Car objects.
public class Garage
{
private Car[] carArray = new Car[4];
// Fill with some Car objects upon startup.
public Garage()
{
carArray[0] = new Car("Rusty", 30);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
}
Ideally, it would be convenient to iterate over the Garage object’s subitems using the foreach construct, just like an array of data values:
// This seems reasonable ...
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n");
Garage carLot = new Garage();
// Hand over each car in the collection?
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.ReadLine();
}
}
Sadly, the compiler informs you that the Garage class does not implement a method named GetEnumerator(). This method is formalized by the IEnumerable interface, which is found lurking within the System.Collections namespace. Classes or structures that support this behavior advertise that they are able to expose contained subitems to the caller (in this example, the foreach keyword itself). Here is the definition of this standard .NET interface:
// This interface informs the caller
// that the object's subitems can be enumerated.
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
As you can see, the GetEnumerator() method returns a reference to yet another interface named System.Collections.IEnumerator. This interface provides the infrastructure to allow the caller to traverse the internal objects contained by the IEnumerable-compatible container:
// This interface allows the caller to
// obtain a container's subitems.
public interface IEnumerator
{
bool MoveNext (); // Advance the internal position of the cursor.
object Current { get;} // Get the current item (read-only property).
void Reset (); // Reset the cursor before the first member.
}
If you want to update the Garage type to support these interfaces, you could take the long road and implement each method manually. While you are certainly free to provide customized versions of GetEnumerator(), MoveNext(), Current, and Reset(), there is a simpler way. As the System.Array type (as well as many other collection classes) already implements IEnumerable and IEnumerator, you can simply delegate the request to the System.Array as follows:
using System.Collections;
...
public class Garage : IEnumerable
{
// System.Array already implements IEnumerator!
private Car[] carArray = new Car[4];
public Garage()
{
carArray[0] = new Car("FeeFee", 200);
carArray[1] = new Car("Clunker", 90);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
public IEnumerator GetEnumerator()
{
// Return the array object's IEnumerator.
return carArray.GetEnumerator();
}
}
After you have updated your Garage type, you can safely use the type within the C# foreach construct. Furthermore, given that the GetEnumerator() method has been defined publicly, the object user could also interact with the IEnumerator type:
// Manually work with IEnumerator.
IEnumerator i = carLot.GetEnumerator();
i.MoveNext();
Car myCar = (Car)i.Current;
Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.CurrentSpeed);
However, if you prefer to hide the functionality of IEnumerable from the object level, simply make use of explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
// Return the array object's IEnumerator.
return carArray.GetEnumerator();
}
By doing so, the casual object user will not find the Garage’s GetEnumerator() method, while the foreach construct will obtain the interface in the background when necessary.
Adapted from the Pro C# 5.0 and the .NET 4.5 Framework
I created a library that allows you to downstep any percentage while keeping all the color data.
https://github.com/danschumann/limby-resize/blob/master/lib/canvas_resize.js
That file you can include in the browser. The results will look like photoshop or image magick, preserving all the color data, averaging pixels, rather than taking nearby ones and dropping others. It doesn't use a formula to guess the averages, it takes the exact average.
It looks like the repos for CentOS 5 are disappearing. Most of the ones mentioned in this question are no longer online, don't seem to have Git, or have a really old version of Git. Below is the script I use to build OpenSSL, IDN2, PCRE, cURL and Git from sources. Both the git://
and https://
protocols will be available for cloning.
Over time the names of the archives will need to be updates. For example, as of this writing, openssl-1.0.2k.tar.gz
is the latest available in the 1.0.2 family.
Dale Anderson's answer using RHEL repos looks good at the moment, but its a fairly old version. Red Hat provides Git version 1.8, while the script below builds 2.12 from sources.
#!/usr/bin/env bash
# OpenSSL installs into lib64/, while cURL installs into lib/
INSTALL_ROOT=/usr/local
INSTALL_LIB32="$INSTALL_ROOT/lib"
INSTALL_LIB64="$INSTALL_ROOT/lib64"
OPENSSL_TAR=openssl-1.0.2k.tar.gz
OPENSSL_DIR=openssl-1.0.2k
ZLIB_TAR=zlib-1.2.11.tar.gz
ZLIB_DIR=zlib-1.2.11
UNISTR_TAR=libunistring-0.9.7.tar.gz
UNISTR_DIR=libunistring-0.9.7
IDN2_TAR=libidn2-0.16.tar.gz
IDN2_DIR=libidn2-0.16
PCRE_TAR=pcre2-10.23.tar.gz
PCRE_DIR=pcre2-10.23
CURL_TAR=curl-7.53.1.tar.gz
CURL_DIR=curl-7.53.1
GIT_TAR=v2.12.2.tar.gz
GIT_DIR=git-2.12.2
###############################################################################
# I don't like doing this, but...
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD
###############################################################################
echo
echo "********** zLib **********"
wget "http://www.zlib.net/$ZLIB_TAR" -O "$ZLIB_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$ZLIB_DIR" &>/dev/null
tar -xzf "$ZLIB_TAR"
cd "$ZLIB_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build zLib"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** Unistring **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.gnu.org/gnu/libunistring/$UNISTR_TAR" --no-check-certificate -O "$UNISTR_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$UNISTR_DIR" &>/dev/null
tar -xzf "$UNISTR_TAR"
cd "$UNISTR_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** IDN **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://alpha.gnu.org/gnu/libidn/$IDN2_TAR" --no-check-certificate -O "$IDN2_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$IDN2_DIR" &>/dev/null
tar -xzf "$IDN2_TAR"
cd "$IDN2_DIR"
LIBS="-ldl -lpthread" ./configure --enable-shared --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build IDN"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** OpenSSL **********"
wget "https://www.openssl.org/source/$OPENSSL_TAR" -O "$OPENSSL_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$OPENSSL_DIR" &>/dev/null
tar -xzf "$OPENSSL_TAR"
cd "$OPENSSL_DIR"
# OpenSSL and enable-ec_nistp_64_gcc_12 option
IS_X86_64=$(uname -m 2>&1 | egrep -i -c "(amd64|x86_64)")
CONFIG=./config
CONFIG_FLAGS=(no-ssl2 no-ssl3 no-comp shared "-Wl,-rpath,$INSTALL_LIB64" --prefix="$INSTALL_ROOT" --openssldir="$INSTALL_ROOT")
if [[ "$IS_X86_64" -eq "1" ]]; then
CONFIG_FLAGS+=("enable-ec_nistp_64_gcc_128")
fi
"$CONFIG" "${CONFIG_FLAGS[@]}"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make depend
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build OpenSSL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install_sw
cd ..
###############################################################################
echo
echo "********** PCRE **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://ftp.pcre.org/pub/pcre//$PCRE_TAR" --no-check-certificate -O "$PCRE_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$PCRE_DIR" &>/dev/null
tar -xzf "$PCRE_TAR"
cd "$PCRE_DIR"
make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
LIBS="-lidn2 -lz -ldl -lpthread" ./configure --enable-shared --enable-pcre2-8 --enable-pcre2-16 --enable-pcre2-32 \
--enable-unicode-properties --enable-pcregrep-libz --prefix="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make all -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build PCRE"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** cURL **********"
# https://savannah.gnu.org/bugs/?func=detailitem&item_id=26786
wget "https://curl.haxx.se/download/$CURL_TAR" --no-check-certificate -O "$CURL_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$CURL_DIR" &>/dev/null
tar -xzf "$CURL_TAR"
cd "$CURL_DIR"
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64 -L$INSTALL_LIB64" \
LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" \
./configure --enable-shared --with-ssl="$INSTALL_ROOT" --with-libidn2="$INSTALL_ROOT" --libdir="$INSTALL_LIB64"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build cURL"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
echo "$SUDO_PASSWWORD" | sudo -S make install
cd ..
###############################################################################
echo
echo "********** Git **********"
wget "https://github.com/git/git/archive/$GIT_TAR" -O "$GIT_TAR"
if [[ "$?" -ne "0" ]]; then
echo "Failed to download Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
rm -rf "$GIT_DIR" &>/dev/null
tar -xzf "$GIT_TAR"
cd "$GIT_DIR"
make configure
CPPFLAGS="-I$INSTALL_ROOT/include" LDFLAGS="-Wl,-rpath,$INSTALL_LIB64,-rpath,$INSTALL_LIB32 -L$INSTALL_LIB64 -L$INSTALL_LIB32" \
LIBS="-lidn2 -lssl -lcrypto -lz -ldl -lpthread" ./configure --with-openssl --with-curl --with-libpcre --prefix="$INSTALL_ROOT"
if [[ "$?" -ne "0" ]]; then
echo "Failed to configure Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
make all -j 4
if [ "$?" -ne "0" ]; then
echo "Failed to build Git"
[[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1
fi
MAKE=make
MAKE_FLAGS=(install)
if [[ ! -z `which asciidoc 2>/dev/null | grep -v 'no asciidoc'` ]]; then
if [[ ! -z `which xmlto 2>/dev/null | grep -v 'no xmlto'` ]]; then
MAKE_FLAGS+=("install-doc" "install-html" "install-info")
fi
fi
echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"
cd ..
###############################################################################
echo
echo "********** Cleanup **********"
rm -rf "$OPENSSL_TAR $OPENSSL_DIR $UNISTR_TAR $UNISTR_DIR $CURL_TAR $CURL_DIR"
rm -rf "$PCRE_TAR $PCRE_DIR $ZLIB_TAR $ZLIB_DIR $IDN2_TAR $IDN2_DIR $GIT_TAR $GIT_DIR"
[[ "$0" = "$BASH_SOURCE" ]] && exit 0 || return 0
simply if you want to create any HTML tag you can try this for example
var selectBody = $('body');
var div = $('<div>');
var h1 = $('<h1>');
var p = $('<p>');
if you want to add any element on the flay you can try this
selectBody.append(div);
By default, iOS only allows HTTPS API. Since HTTP is not secure, you will have to disable App transport security. There are two ways to disable ATS:-
1. Adding source code in project info.plist and add the following code in root tag.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
2. Using project info.
Click on project on the project on the left pane, select the project as target and choose info tab. You have to add the dictionary in the following structure.
Wasted 4+ hours on this.
I have Visual Studio 2017 Enterprise, one of the projects has below error:
The builds tools for v120 (Platform Toolset = 'v120') cannot be found
To resolve above error, I tried to install all below:
However, none of the above worked.
Later, installed Visual Studio 2013 Ultimate, then all worked fine.
Looks like, the older Visual studio is a must to resolve this.
Hope it helps.
Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:
uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);
The destination type will blindly pick the 32 bits and reinterpret them.
Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:
uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);
In this case, you'll get overflow exceptions if:
In our case, we wanted the unchecked
solution to preserve the 32bits as-is, so here are some examples:
int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)
uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------
int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };
foreach (var Int in testInts)
{
uint asUint = unchecked((uint)Int);
Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
int asInt = unchecked((int)Uint);
Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
Console.WriteLine(new string('-', 30));
}
ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
By far the best solution I've seen that is CSS only, with good cross browser support, and no alignment issues is this solution from codingrabbithole
table {
width: 100%;
}
thead, tbody tr {
display: table;
width: 100%;
table-layout: fixed;
}
tbody {
display: block;
overflow-y: auto;
table-layout: fixed;
max-height: 200px;
}
A more "precise" calculation. That is, the number of week/month/quarter/year for a non-complete week/month/quarter/year is the fraction of calendar days in that week/month/quarter/year. For example, the number of months between 2016-02-22 and 2016-03-31 is 8/29 + 31/31 = 1.27586
explanation inline with code
#' Calculate precise number of periods between 2 dates
#'
#' @details The number of week/month/quarter/year for a non-complete week/month/quarter/year
#' is the fraction of calendar days in that week/month/quarter/year.
#' For example, the number of months between 2016-02-22 and 2016-03-31
#' is 8/29 + 31/31 = 1.27586
#'
#' @param startdate start Date of the interval
#' @param enddate end Date of the interval
#' @param period character. It must be one of 'day', 'week', 'month', 'quarter' and 'year'
#'
#' @examples
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "month"), 15/29 + 1)
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "quarter"), (15 + 31)/(31 + 29 + 31))
#' identical(numPeriods(as.Date("2016-02-15"), as.Date("2016-03-31"), "year"), (15 + 31)/366)
#'
#' @return exact number of periods between
#'
numPeriods <- function(startdate, enddate, period) {
numdays <- as.numeric(enddate - startdate) + 1
if (grepl("day", period, ignore.case=TRUE)) {
return(numdays)
} else if (grepl("week", period, ignore.case=TRUE)) {
return(numdays / 7)
}
#create a sequence of dates between start and end dates
effDaysinBins <- cut(seq(startdate, enddate, by="1 day"), period)
#use the earliest start date of the previous bins and create a breaks of periodic dates with
#user's period interval
intervals <- seq(from=as.Date(min(levels(effDaysinBins)), "%Y-%m-%d"),
by=paste("1",period),
length.out=length(levels(effDaysinBins))+1)
#create a sequence of dates between the earliest interval date and last date of the interval
#that contains the enddate
allDays <- seq(from=intervals[1],
to=intervals[intervals > enddate][1] - 1,
by="1 day")
#bin all days in the whole period using previous breaks
allDaysInBins <- cut(allDays, intervals)
#calculate ratio of effective days to all days in whole period
sum( tabulate(effDaysinBins) / tabulate(allDaysInBins) )
} #numPeriods
Please let me know if you find more boundary cases where the above solution does not work.
If you are using moment.js:
moment().month("Jan").format("M");
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
In my situation, some pods were out of date after I updated my OS. Here's what fixed it:
In terminal:
cd /Users/quaisafzali/Desktop/AppFolder/Application/
pod install
Then, open your project in Xcode and Clean it (Cmd+Shift+K), then Build/Run.
This worked for me, hope it helps some of you!
In my case the built address of my app was set to another computer that was turned off so i turned it on and restart VS and problem solved.
--Similar answer as above for the most part. Code included to test
DROP TABLE table1
GO
CREATE TABLE table1 (project int, customer int, company int, product int, price money)
GO
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
GO
SELECT TOP 1 WITH TIES product
, price
, CASE WhereFound WHEN 1 THEN 'Project'
WHEN 2 THEN 'Customer'
WHEN 3 THEN 'Company'
ELSE 'No Match'
END AS Source
FROM
(
SELECT product, price, 1 as WhereFound FROM table1 where project = 11
UNION ALL
SELECT product, price, 2 FROM table1 where customer = 0
UNION ALL
SELECT product, price, 3 FROM table1 where company = 30
) AS tbl
ORDER BY WhereFound ASC
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
Yes, both will give you deferred execution.
The difference is that IQueryable<T>
is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>
, that query will be executed in the database, if possible.
For the IEnumerable<T>
case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:
IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
This is quite an important difference, and working on IQueryable<T>
can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take
and Skip
on IQueryable
, you will only get the number of rows requested; doing that on an IEnumerable<T>
will cause all of your rows to be loaded in memory.
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
You can download the latest mysql driver jar from below path, and copy to your classpath or if you are using web server then copy to tomcat/lib or war/web-inf/lib folder.
Check if your scripts name doesn't contain $SERVICE. If it does, it will be shown in ps results, causing script to always think that service is running. You can grep it against current filename like this:
#!/bin/sh
SERVICE=$1
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi
One thing that should be considered is licensing.
Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.
To quote the Sublime Text 2 website:
..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.
The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.
Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.
This licensing requirement is still correct as of Dec 2019.
Use attribute binding syntax instead
<ol class="viewer-nav"><li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value">{{ section.text }}</li>
</ol>
or
<ol class="viewer-nav"><li *ngFor="let section of sections"
attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>
</ol>
Brother you don't need to set class path just follow these simple steps (I use Apache NetBeans)
Steps:
extract the jar file which you want to add in your project.
only copy those packages (folder) which you need in the project. (do not copy manifest file)
open the main project jar file(dist/file.jar) with WinRAR.
paste that folder or package in the main project jar file.
Those packages work 100% in your project.
warning: Do not make any changes in the manifest file.
Another method:
we need to move lib folder in dist folder.then we set class path from manifest.mf file of main jar file.
Edit the manifest.mf And ADD this type of line
Warning: lib folder must be inside the dist folder otherwise jar file do not access your lib folder jar files
Simple way to deal with merging single array values.
var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}
var object=null;
var first=values[0];
for (var i in values)
if(i>0)
object= $.merge(values[i],first)
select to_char(sysdate,'DAY') from dual; It's work try it
var token = 'spo';
switch(token){
case ( (token.match(/spo/) )? token : undefined ) :
console.log('MATCHED')
break;;
default:
console.log('NO MATCH')
break;;
}
--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case
--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.
The ternary test can be anything for instance in your case
( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined
===========================================
(token.match(/spo/) )? token : undefined )
is a ternary expression.
The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).
If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).
Obviously token === token so the switch statement is matched and the case evaluated
It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.
Alternatively, you can get a convenient list of commands coupled with quick descriptions (as long as the command has a man page, which most do):
apropos -s 1 ''
-s 1 returns only "section 1" manpages which are entries for executable programs.
'' is a search for anything. (If you use an asterisk, on my system, bash throws in a search for all the files and folders in your current working directory.)
Then you just grep it like you want.
apropos -s 1 '' | grep xdg
yields:
xdg-desktop-icon (1) - command line tool for (un)installing icons to the desktop
xdg-desktop-menu (1) - command line tool for (un)installing desktop menu items
xdg-email (1) - command line tool for sending mail using the user's preferred e-mail composer
xdg-icon-resource (1) - command line tool for (un)installing icon resources
xdg-mime (1) - command line tool for querying information about file type handling and adding descriptions for new file types
xdg-open (1) - opens a file or URL in the user's preferred application
xdg-screensaver (1) - command line tool for controlling the screensaver
xdg-settings (1) - get various settings from the desktop environment
xdg-user-dir (1) - Find an XDG user dir
xdg-user-dirs-update (1) - Update XDG user dir configuration
The results don't appear to be sorted, so if you're looking for a long list, you can throw a | sort | into the middle, and then pipe that to a pager like less/more/most. ala:
apropos -s 1 '' | sort | grep zip | less
Which returns a sorted list of all commands that have "zip" in their name or their short description, and pumps that the "less" pager. (You could also replace "less" with $PAGER and use the default pager.)
You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.
However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.
IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:
overflow: auto;
overflow-y: hidden;
You may also need to add for IE8:
-ms-overflow-y: hidden;
as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)
On the other hand it's entirely possible IE8 will have fixed the bug anyway.
Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main
import (
"fmt"
"reflect"
)
type person struct {
firsName string
lastName string
iceCream []string
}
func main() {
u := struct {
myMap map[int]int
mySlice []string
myPerson person
}{
myMap: map[int]int{1: 10, 2: 20},
mySlice: []string{"red", "green"},
myPerson: person{
firsName: "Esmaeil",
lastName: "Abedi",
iceCream: []string{"Vanilla", "chocolate"},
},
}
v := reflect.ValueOf(u)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println("\t", v.Field(i))
}
}
and there is no *panic* for v.Field(i)
For those not getting the -ms-border-radius: or the border-radius: to work in IE 10,11 And it renders all square then follow these steps:
Differences:
The return type of RenderPartial
is void
, where as Partial
returns MvcHtmlString
Syntax for invoking Partial()
and RenderPartial()
methods in Razor views
@Html.Partial("PartialViewName")
@{ Html.RenderPartial("PartialViewName"); }
Syntax for invoking Partial()
and RenderPartial()
methods in webform views
[%: Html.Partial("PartialViewName") %]
[% Html.RenderPartial("PartialViewName"); %]
The following are the 2 common interview questions related to Partial()
and RenderPartial()
When would you use Partial()
over RenderPartial()
and vice versa?
The main difference is that RenderPartial()
returns void and the output will be written directly to the output stream, where as the Partial()
method returns MvcHtmlString
, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().
Which one is better for performance?
From a performance perspective, rendering directly to the output stream is better. RenderPartial()
does exactly the same thing and is better for performance over Partial()
.
If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -
Var x = "hello_world";
x[0]; //h
x[x.length-1]; //d
Yet if you need more than just one character then use splice is effective
x.slice(-5); //world
Regarding your example
"rating_element-<?php echo $id?>"
To extract id you can easily use split + pop
Id= inputId.split('rating_element-')[1];
This will return the id, or undefined if no id was after 'rating_element' :)
You can either use the prepareStatement
method taking an additional int
parameter
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:
PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})
async
is now an independent module : grequests
.
See here : https://github.com/kennethreitz/grequests
And there: Ideal method for sending multiple HTTP requests over Python?
$ pip install grequests
build a stack:
import grequests
urls = [
'http://www.heroku.com',
'http://tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
rs = (grequests.get(u) for u in urls)
send the stack
grequests.map(rs)
result looks like
[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]
grequests don't seem to set a limitation for concurrent requests, ie when multiple requests are sent to the same server.
To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.
Another way is to type yourmodelname$
and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients
, you will see all of beta-, p, and t- values you desire.
The normal way would be the IF statement, though simpler than your example:
=IF(INDEX(a,b,c),INDEX(a,b,c),"")
No need to do gyrations with the formula, since zero values trigger the false condition.
Here is what seems simplest and works in python 3.7
from collections import OrderedDict
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d) # Now a normal dict
Now to check this:
>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True
NOTE: This also works, and gives same result -
>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True
As well as this -
>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True
Cheers
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
Two options:
libimobiledevice is installable via homebrew and works great. Its idevicesyslog
tool works similarly to deviceconsole
(below), and it supports wirelessly viewing your device's syslog (!)
I've written more about that on Tumblr tl;dr:
brew install libimobiledevice
idevice_id --list // list available device UDIDs
idevicesyslog -u <device udid>
with the device connected via USB or available on the local wireless network.
(Keeping for the historical record, from 2013:) deviceconsole from rpetrich is a much less wacked-out solution than ideviceconsole above. My fork of it builds and runs in Xcode 5 out of the box, and the Build action will install the binary to /usr/local/bin
for ease of use.
As an additional helpful bit of info, I use it in the following style which makes it easy to find the device I want in my shell history and removes unnecessary >
lines that deviceconsole
prints out.
deviceconsole -d -u <device UDID> | uniq -u && echo "<device name>"
short answer, specific to OAuth2,
I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).
Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.
You could also adjust the precision of your float in the database.
It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<center>
<body>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("rachna",$con);
$query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'A' GROUP BY Iyear";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo "<table><tr><th></th><th>1999</th><th>2000</th><th>2001</th><th>2003</th></tr>";
echo "<th>A</th>";
//Code for A Customer-------------------------------------------
while($row =mysql_fetch_array($result)) {
echo "<th>" . $row['RESULT'] . "</th>";
}
echo"<tr></tr>";
//COde of B Customer--------------------------------------
echo "<th>B</th>";
$query = "SELECT SUM( Ivalue ) AS RESULT FROM loan WHERE cname = 'B' GROUP BY Iyear";
$result1 = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result1)) {
echo "<th> " . $row["RESULT"]. "</th>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</center>
</body>
</html>
Try using *
unpack, like below:
>>> a=set('abcde')
>>> a
{'a', 'd', 'e', 'b', 'c'}
>>> l=['f','g']
>>> l
['f', 'g']
>>> {*l, *a}
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
>>>
Non Editor version:
a=set('abcde')
l=['f', 'g']
print({*l, *a})
Output:
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
Just want to share my button style from my ResourceDictionary that i've been using. You can freely change the onHover background at the style triggers. "ColorAnimation To = *your desired BG(i.e #FFCEF7A0)". The button BG will also automatically revert to its original BG after the mouseOver state.You can even set how fast the transition.
Resource Dictionary
<Style x:Key="Flat_Button" TargetType="{x:Type Button}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="FontFamily" Value="Arial Narrow"/>
<Setter Property="FontSize" Value="12px"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Opacity="1" Color="White"/>
</Setter.Value>
</Setter>
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Opacity="1" Color="#28C2FF" />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border"
SnapsToDevicePixels="True"
BorderThickness="1"
Padding="4,2"
BorderBrush="Gray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<Grid>
<ContentPresenter
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="#D2F898"
Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
all you have to do is call the style.
Example Implementation
<Button Style="{StaticResource Flat_Button}" Height="Auto"Width="Auto">
<StackPanel>
<TextBlock Text="SAVE" FontFamily="Arial" FontSize="10.667"/>
</StackPanel>
</Button>
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
As noted in the official documentation, simply apply the class(es) btn btn-link
:
<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>
For example, with the code you have provided:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
<div class="row-fluid">_x000D_
<!-- Navigation for the form -->_x000D_
<div class="span3">_x000D_
<ul class="nav nav-tabs nav-stacked">_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
</li>_x000D_
<li>_x000D_
<button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
</li>_x000D_
<!-- ... -->_x000D_
</ul>_x000D_
</div>_x000D_
<!-- The actual form -->_x000D_
<div class="span9">_x000D_
<!-- ... -->_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.
It's a double-edged sword. It is sometimes very useful, but often dangerous.
When is it good? When you want 10 cases all processed the same way...
switch (c) {
case 1:
case 2:
... Do some of the work ...
/* FALLTHROUGH */
case 17:
... Do something ...
break;
case 5:
case 43:
... Do something else ...
break;
}
The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.
All the approaches described did not work for me because I was adding the click event with on()
to the document where the element was created at run-time:
$(document).on("click", ".button", function() {
doSomething();
});
My workaround:
As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:
// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");
Hope that helps.
Dominc has the right idea, but put the calculation on the other side of the expression.
SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)
This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
Ooor you just create your own ListIterator:
public final class SparseArrayIterator<E> implements ListIterator<E> {
private final SparseArray<E> array;
private int cursor;
private boolean cursorNowhere;
/**
* @param array
* to iterate over.
* @return A ListIterator on the elements of the SparseArray. The elements
* are iterated in the same order as they occur in the SparseArray.
* {@link #nextIndex()} and {@link #previousIndex()} return a
* SparseArray key, not an index! To get the index, call
* {@link android.util.SparseArray#indexOfKey(int)}.
*/
public static <E> ListIterator<E> iterate(SparseArray<E> array) {
return iterateAt(array, -1);
}
/**
* @param array
* to iterate over.
* @param key
* to start the iteration at. {@link android.util.SparseArray#indexOfKey(int)}
* < 0 results in the same call as {@link #iterate(android.util.SparseArray)}.
* @return A ListIterator on the elements of the SparseArray. The elements
* are iterated in the same order as they occur in the SparseArray.
* {@link #nextIndex()} and {@link #previousIndex()} return a
* SparseArray key, not an index! To get the index, call
* {@link android.util.SparseArray#indexOfKey(int)}.
*/
public static <E> ListIterator<E> iterateAtKey(SparseArray<E> array, int key) {
return iterateAt(array, array.indexOfKey(key));
}
/**
* @param array
* to iterate over.
* @param location
* to start the iteration at. Value < 0 results in the same call
* as {@link #iterate(android.util.SparseArray)}. Value >
* {@link android.util.SparseArray#size()} set to that size.
* @return A ListIterator on the elements of the SparseArray. The elements
* are iterated in the same order as they occur in the SparseArray.
* {@link #nextIndex()} and {@link #previousIndex()} return a
* SparseArray key, not an index! To get the index, call
* {@link android.util.SparseArray#indexOfKey(int)}.
*/
public static <E> ListIterator<E> iterateAt(SparseArray<E> array, int location) {
return new SparseArrayIterator<E>(array, location);
}
private SparseArrayIterator(SparseArray<E> array, int location) {
this.array = array;
if (location < 0) {
cursor = -1;
cursorNowhere = true;
} else if (location < array.size()) {
cursor = location;
cursorNowhere = false;
} else {
cursor = array.size() - 1;
cursorNowhere = true;
}
}
@Override
public boolean hasNext() {
return cursor < array.size() - 1;
}
@Override
public boolean hasPrevious() {
return cursorNowhere && cursor >= 0 || cursor > 0;
}
@Override
public int nextIndex() {
if (hasNext()) {
return array.keyAt(cursor + 1);
} else {
throw new NoSuchElementException();
}
}
@Override
public int previousIndex() {
if (hasPrevious()) {
if (cursorNowhere) {
return array.keyAt(cursor);
} else {
return array.keyAt(cursor - 1);
}
} else {
throw new NoSuchElementException();
}
}
@Override
public E next() {
if (hasNext()) {
if (cursorNowhere) {
cursorNowhere = false;
}
cursor++;
return array.valueAt(cursor);
} else {
throw new NoSuchElementException();
}
}
@Override
public E previous() {
if (hasPrevious()) {
if (cursorNowhere) {
cursorNowhere = false;
} else {
cursor--;
}
return array.valueAt(cursor);
} else {
throw new NoSuchElementException();
}
}
@Override
public void add(E object) {
throw new UnsupportedOperationException();
}
@Override
public void remove() {
if (!cursorNowhere) {
array.remove(array.keyAt(cursor));
cursorNowhere = true;
cursor--;
} else {
throw new IllegalStateException();
}
}
@Override
public void set(E object) {
if (!cursorNowhere) {
array.setValueAt(cursor, object);
} else {
throw new IllegalStateException();
}
}
}
If you can't change the type of your input array the following will work:
final int[] data = new int[] { 5, 4, 2, 1, 3 };
final Integer[] sorted = ArrayUtils.toObject(data);
Arrays.sort(sorted, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
// Intentional: Reverse order for this demo
return o2.compareTo(o1);
}
});
System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);
This uses ArrayUtils
from the commons-lang project to easily convert between int[]
and Integer[]
, creates a copy of the array, does the sort, and then copies the sorted data over the original.
StringBuilder sb = new StringBuilder();
sb.append("abcdef");
sb.deleteCharAt(sb.length() - 1);
assertEquals("abcde",sb.toString());
// true
git cherry-pick
: Apply the changes introduced by some existing commits
Assume we have branch A with (X, Y, Z) commits. We need to add these commits to branch B. We are going to use the cherry-pick
operations.
When we use cherry-pick
, we should add commits on branch B in the same chronological order that the commits appear in Branch A.
cherry-pick does support a range of commits, but if you have merge commits in that range, it gets really complicated
git checkout B
git cherry-pick SHA-COMMIT-X
git cherry-pick SHA-COMMIT-Y
git cherry-pick SHA-COMMIT-Z
Example of workflow :
We can use cherry-pick
with options
-e or --edit : With this option, git cherry-pick will let you edit the commit message prior to committing.
-n or --no-commit : Usually the command automatically creates a sequence of commits. This flag applies the changes necessary to cherry-pick each named commit to your working tree and the index, without making any commit. In addition, when this option is used, your index does not have to match the HEAD commit. The cherry-pick is done against the beginning state of your index.
Here an interesting article concerning cherry-pick
.
If you are after the side effects that happen within the loop, I'd personally go for the range()
approach.
If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or map
approach. Something like this:
def f(n):
return n * n
results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))
Here is a link to video called ‘Classic Database Development Mistakes and five ways to overcome them’ by Scott Walz
If still all the above doen't work you can always add to the script
set "JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
I use a piece of code that i developed myself and it is pretty good for my codes:
In the beginning of the function or sub, I define:
On error Goto ErrorCatcher:
and then, I handle the possible errors
ErrorCatcher:
Select Case Err.Number
Case 0 'exit the code when no error was raised
On Error GoTo 0
Exit Function
Case 1 'Error on definition of object
'do stuff
Case... 'little description here
'do stuff
Case Else
Debug.Print "###ERROR"
Debug.Print " • Number :", Err.Number
Debug.Print " • Descrip :", Err.Description
Debug.Print " • Source :", Err.Source
Debug.Print " • HelpCont:", Err.HelpContext
Debug.Print " • LastDLL :", Err.LastDllError
Stop
Err.Clear
Resume
End Select
The TRUNCATE statement was my first problem, glad to find the solution here. But I was using SSIS and trying to load data from another database, and it failed with the same error on any table that used IDENTITY to create an auto-incrementing ID. If I was scripting it myself I'd first need to use the command SET IDENTITY_INSERT tablename ON, and then SET IDENTITY_INSERT tablename OFF when the table update was done. But this requires ALTER permissions on the table, which I do not have. Hence the error message in SSIS on the table load (even though the previous step had just deleted all the data out of the table.)
if (-not ([string]::IsNullOrEmpty($version)))
{
$request += "/" + $version
}
You can also use !
as an alternative to -not
.
ooh! neat question.
Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.
here's an example which may help illustrate:
>> A = zeros(4); A(:) = 1:16
A =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
>> A
A =
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Yes, you can use the built-in hashlib
module or the built-in hash
function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:
>>> s = 'she sells sea shells by the sea shore'
>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L
>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.
In htaccess:
SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
in index.php
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
// instead of mapping:
$app->options('/(:x+)', function() use ($app) {
//...return correct headers...
$app->response->setStatus(200);
});
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
Hope This useful...
form:
<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>
check.php:
<?php
if(isset($_POST['upload'])){
$maxsize=2097152;
$format=array('image/jpeg');
if($_FILES['file_upload']['size']>=$maxsize){
$error_1='File Size too large';
echo '<script>alert("'.$error_1.'")</script>';
}
elseif($_FILES['file_upload']['size']==0){
$error_2='Invalid File';
echo '<script>alert("'.$error_2.'")</script>';
}
elseif(!in_array($_FILES['file_upload']['type'],$format)){
$error_3='Format Not Supported.Only .jpeg files are accepted';
echo '<script>alert("'.$error_3.'")</script>';
}
else{
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){
echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
}
else{
echo "sorry";
}
}
}
?>
Your command
ps | egrep 11383 | cut -d" " -f 4
misses a tr -s
to squeeze spaces, as unwind explains in his answer.
However, you maybe want to use awk
, since it handles all of these actions in a single command:
ps | awk '/11383/ {print $4}'
This prints the 4th column in those lines containing 11383
. If you want this to match 11383
if it appears in the beginning of the line, then you can say ps | awk '/^11383/ {print $4}'
.
I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...
Here's what I came up with:
python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"
That's the one-liner, here's it a little more readable:
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)
This worked for downloading a tarball. I was able to extract the package and download it after downloading.
EDIT:
To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint
package, but this was tested on my machine and works fine:
#!/usr/bin/env python
from clint.textui import progress
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
total_length = int(r.headers.get('content-length'))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1):
if chunk:
f.write(chunk)
f.flush()
JFrame
is the window; it can have one or more JPanel
instances inside it. JPanel
is not the window.
You need a Swing tutorial:
Update on the accepted answer:
Because of many properties becoming deprecated
(property) KeyboardEvent.which: number @deprecated
you should just rely on the key property and create the rest of the logic by yourself:
The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.
document.querySelector("input").addEventListener("keypress", (e) => {
if (isNaN(parseInt(e.key, 10)) && e.key !== "Backspace" && e.key !== "Enter") {
e.preventDefault();
}
});
NOTE This will disable paste action
You could have used DISTINCT
or just remove the PARTITION BY
portions and use GROUP BY
:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount)
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER ()
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix
if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
//do something
if(f1!=null){f1();}
}
then somewhere else...
if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
//do something else
if(f2!=null){f2();}
}
this will update the onload function and chain as needed
if you work with pandas
what solved the issue for me was that i was trying to do calculations when I had NA values, the solution was to run:
df = df.dropna()
And after that the calculation that failed.
From the docs:
If you want to provide others with a static HTML or PDF view of your notebook, use the Print button. This opens a static view of the document, which you can print to PDF using your operating system’s facilities, or save to a file with your web browser’s ‘Save’ option (note that typically, this will create both an html file and a directory called notebook_name_files next to it that contains all the necessary style information, so if you intend to share this, you must send the directory along with the main html file).
A simple dplyr based reordering of factors can solve this problem:
library(dplyr)
#reorder the table and reset the factor to that ordering
theTable %>%
group_by(Position) %>% # calculate the counts
summarize(counts = n()) %>%
arrange(-counts) %>% # sort by counts
mutate(Position = factor(Position, Position)) %>% # reset factor
ggplot(aes(x=Position, y=counts)) + # plot
geom_bar(stat="identity") # plot histogram
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.
new string
(stringToRemoveWhiteSpaces
.Where
(
c => !char.IsWhiteSpace(c)
)
.ToArray<char>()
)
OR
new string
(stringToReplaceWhiteSpacesWithSpace
.Select
(
c => char.IsWhiteSpace(c) ? ' ' : c
)
.ToArray<char>()
)
Just use x["error_msg"]
. If the property doesn't exist, it returns null
.
You can also stringify the object and then again parse to make the normal object. For example like:-
const obj = JSON.parse(JSON.stringify(mongoObj))
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.
That said, here's what you have to do if you're determined to make this work:
Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).
In the head of your template, include {{ form.media }} to output the links to the Javascript files.
And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
You may also wish to use the following admin CSS (thanks Alex for mentioning this):
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.
This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf:
(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),
Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
Thanks lupefiasco for this addition.
This is not a question about make, it is a question about the semantic of the #include
directive.
The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include
directive "StdCUtil/split.h".
To fix this, just use -I..
instead of -I../StdCUtil
.
First, disabling the index during the deletion would be helpful.
Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following
MERGE INTO table1 src
USING (SELECT id,col1
FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
UPDATE
SET src.col1 = tgt.col1
DELETE
WHERE src.id = tgt.id
Just a note to the answer done by James Sulak.
If you want to take into consideration that the node may not exist and want to keep it purely XPATH, then try the following that will return 0 if the node does not exist.
count(a/b[.='tsr']/preceding-sibling::*)+number(boolean(a/b[.='tsr']))
When using React hooks there is no access to access to this.props.location
.
To capture url parameters use window
object.
const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');
pkill -9 rails
to kill all the process of rails
Updated answer
ps aux|grep 'rails'|grep -v 'grep'|awk '{ print $2 }'|xargs kill -9
This will kill any running rails process. Replace 'rails' with something else to kill any other processes.
The simplest way is:
make foo=bar target
Then in your makefile you can refer to $(foo)
. Note that this won't propagate to sub-makes automatically.
If you are using sub-makes, see this article: Communicating Variables to a Sub-make
I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..
ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...
Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )
In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..
I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...
P.S I cant get source code before the weekend since external SSH is disabled in my office :(
This is how it should be done in typescript:
(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()
Better readability:
var eventStartTime = new Date(event.startTime);
var eventEndTime = new Date(event.endTime);
var duration = eventEndTime.valueOf() - eventStartTime.valueOf();
I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.
The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.
.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:
OPTIONAL HEADER VALUES
10B magic # (PE32)
...
4.00 operating system version
0.00 image version
4.00 subsystem version // <=== here!!
0 Win32 version
...
What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.
You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.
That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0
And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0
Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.
Try one of these:
ApplicationRef.tick()
- similar to AngularJS's $rootScope.$digest()
-- i.e., check the full component treeNgZone.run(callback)
- similar to $rootScope.$apply(callback)
-- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.ChangeDetectorRef.detectChanges()
- similar to $scope.$digest()
-- i.e., check only this component and its childrenYou can inject ApplicationRef
, NgZone
, or ChangeDetectorRef
into your component.
Try this code once-
public class FindPeopleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home,
container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateDetail();
}
});
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), MainActivityList.class);
startActivity(intent);
}
}
And as suggested by Raghunandan remove below code from your fragment_home.xml
-
android:onClick="goToAttract"
This is because you probably have close the Metro Bundler Window or it might be crashed. just open another terminal/cmd in the project directory and run npm start
. By Running npm start
React Native will launch the MetroBundler Window once again. After bundler finishes the BUNDLE
process, just reload the Application and you will be good to go.
I've been using:
@media only screen and (min-width: 768px) {
/* tablets and desktop */
}
@media only screen and (max-width: 767px) {
/* phones */
}
@media only screen and (max-width: 767px) and (orientation: portrait) {
/* portrait phones */
}
It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).
Here's my expression dark theme for WPF controls.
There seems a different consensus in the C# and Java camps on this. The majority of Java code I have seen uses:
// apply mutex to this instance
synchronized(this) {
// do work here
}
whereas the majority of C# code opts for the arguably safer:
// instance level lock object
private readonly object _syncObj = new object();
...
// apply mutex to private instance level field (a System.Object usually)
lock(_syncObj)
{
// do work here
}
The C# idiom is certainly safer. As mentioned previously, no malicious / accidental access to the lock can be made from outside the instance. Java code has this risk too, but it seems that the Java community has gravitated over time to the slightly less safe, but slightly more terse version.
That's not meant as a dig against Java, just a reflection of my experience working on both languages.
First - Copy CON SETUPDAY.001 SET WORKDAY=^Z (very important - no cr/lf)
DATE /T >SETUPDAY.002
COPY SETUPDAY.001+SETUPDAY.002 NEWDAY.BAT >nul
CALL NEWDAY.BAT
SET WEEKDAY=%WORKDAY:~0,3%
SET MDY=%WORKDAY:~4,10%
USE %WEEKDAY% IN YOUR SCRIPT
I thought up a rather elegant solution (IMHO), so I can't resist posting it:
from bisect import bisect_left
class Interpolate(object):
def __init__(self, x_list, y_list):
if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
raise ValueError("x_list must be in strictly ascending order!")
x_list = self.x_list = map(float, x_list)
y_list = self.y_list = map(float, y_list)
intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
self.slopes = [(y2 - y1)/(x2 - x1) for x1, x2, y1, y2 in intervals]
def __getitem__(self, x):
i = bisect_left(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
I map to float
so that integer division (python <= 2.7) won't kick in and ruin things if x1
, x2
, y1
and y2
are all integers for some iterval.
In __getitem__
I'm taking advantage of the fact that self.x_list is sorted in ascending order by using bisect_left
to (very) quickly find the index of the largest element smaller than x
in self.x_list
.
Use the class like this:
i = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
# Get the interpolated value at x = 4:
y = i[4]
I've not dealt with the border conditions at all here, for simplicity. As it is, i[x]
for x < 1
will work as if the line from (2.5, 4) to (1, 2) had been extended to minus infinity, while i[x]
for x == 1
or x > 6
will raise an IndexError
. Better would be to raise an IndexError in all cases, but this is left as an exercise for the reader. :)
Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.
Consider Android Development:
IDE: Eclipse etc..
Library: android.app.Activity library (Class with all code)
API: Interface basically all functions with which we call
SDK: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android (----tools - DDMS,Emulator ----platforms - Android OS versions, ----platform-tools - ADB, ----API docs)
ToolKit: Could be ADT Bundle
Framework: Big library but more of architecture-oriented
dir /s /b /a:d>output.txt
will port it to a text file
If you're interested in a data.table
solution, here's one. It's a bit tricky since you prefer to get the id for the first maximum. It's much easier if you'd rather want the last maximum. Nevertheless, it's not that complicated and it's fast!
Here I've generated data of your dimensions (26746 * 18).
set.seed(45)
DF <- data.frame(matrix(sample(10, 26746*18, TRUE), ncol=18))
data.table
answer:require(data.table)
DT <- data.table(value=unlist(DF, use.names=FALSE),
colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]
# data.table solution
system.time({
DT <- data.table(value=unlist(DF, use.names=FALSE),
colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]
})
# user system elapsed
# 0.174 0.029 0.227
# apply solution from @thelatemail
system.time(t2 <- colnames(DF)[apply(DF,1,which.max)])
# user system elapsed
# 2.322 0.036 2.602
identical(t1, t2)
# [1] TRUE
It's about 11 times faster on data of these dimensions, and data.table
scales pretty well too.
DT <- data.table(value=unlist(DF, use.names=FALSE),
colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid)), rowid, mult="last"]
In my case, it was a permissions issue.
For the Windows user, I was using did not have dbcreator
role.
So I followed the below steps
sa
to the SQL serverSecurity
in Object ExplorerLogins
Server Roles
from Select a page
optionsdbcreator
role for the user There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))
You can use system-dependant commands like
Runtime rt = Runtime.getRuntime();
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1)
rt.exec("taskkill " +....);
else
rt.exec("kill -9 " +....);
You can use the following format to generate a tooltip for an image.
<div class="tooltip"><img src="joe.jpg" />
<span class="tooltiptext">Tooltip text</span>
</div>
According to: https://docs.npmjs.com/files/folders
- Local install (default): puts stuff in ./node_modules of the current package root.
- Global install (with -g): puts stuff in /usr/local or wherever node is installed.
- Install it locally if you're going to require() it.
- Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.
prefix Configuration
The prefix config defaults to the location where node is installed. On most systems, this is
/usr/local
. On windows, this is the exact location of the node.exe binary.
The docs might be a little outdated, but they explain why global installs can end up in different directories:
(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"
Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.
This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):
mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm
open a new cmd.exe window and reinstall all global packages.
Explanation (by lineno.):
setx .. /M
to set the
system path (under HKEY_LOCAL_MACHINE). This is what requires you to run
this in a shell with administrator permissions.npm
to use this new path. (Note: folder isn't visible in %PATH% in
this shell, so you must open a new window).select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)
Since it was a successful comment, I am adding it as an answer:
with files:
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
In Python 3.6+ you could use Variable Annotations for this:
https://www.python.org/dev/peps/pep-0526/#abstract
PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:
# 'captain' is a string (Note: initial value is a problem)
captain = ... # type: str
PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:
captain: str # Note: no initial value!
It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"
What version of the framework? With 3.5 you could presumably use:
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
(edited to remove simpler version; I checked and ManagementObjectCollection
only implements the non-generic IEnumerable
form)
Load url helper in controller
$this->load->helper('url');
As per this answer, you can use the jQuery load event on the window
object instead of the document
:
jQuery(window).load(function() {
console.log("page finished loading now.");
});
This will be triggered after all content on the page has been loaded. This differs from jQuery(document).load(...)
which is triggered after the DOM has finished loading.
By default, oracle date subtraction returns a result in # of days.
So just multiply by 24 to get # of hours, and again by 60 for # of minutes.
Example:
select
round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
(
select
to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
from
dual
) test_data
Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.
The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.
This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
Hope this helps.
I had a similar situation, where my master branch and the develop branch I was trying to merge had different commit histories. None of the above solutions worked for me. What did the trick was:
Starting from master:
git branch new_branch
git checkout new_branch
git merge develop --allow-unrelated-histories
Now in the new_branch, there are all the things from develop and I can easily merge into master, or create a pull request, as they now share the same commit hisotry.
Since the default for block elements is to order one on top of the other you should also be able to do this:
<div>
<img src="path/to/img">
<div>Text Under Image</div>
</div
img {
display: block;
}
Since appcompat-v7-r23 you can use the following attributes directly on your Toolbar
or its style:
app:titleTextColor="@color/primary_text"
app:subtitleTextColor="@color/secondary_text"
If your minimum SDK is 23 and you use native Toolbar
just change the namespace prefix to android
.
In Java you can use the following methods:
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);
These methods take a color int not a color resource ID!
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.MyApp.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
style="@style/Widget.MyApp.Toolbar.Solid"/>
<style name="Widget.MyApp.Toolbar.Solid" parent="Widget.AppCompat.ActionBar">
<item name="android:background">@color/actionbar_color</item>
<item name="android:elevation" tools:ignore="NewApi">4dp</item>
<item name="titleTextAppearance">...</item>
</style>
<style name="ThemeOverlay.MyApp.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
<!-- Parent theme sets colorControlNormal to textColorPrimary. -->
<item name="android:textColorPrimary">@color/actionbar_title_text</item>
</style>
@PeterKnut reported this affects the color of overflow button, navigation drawer button and back button. It also changes text color of SearchView
.
Concerning the icon colors: The colorControlNormal
inherits from
android:textColorPrimary
for dark themes (white on black)android:textColorSecondary
for light themes (black on white)If you apply this to the action bar's theme, you can customize the icon color.
<item name="colorControlNormal">#de000000</item>
There was a bug in appcompat-v7 up to r23 which required you to also override the native counterpart like so:
<item name="android:colorControlNormal" tools:ignore="NewApi">?colorControlNormal</item>
Note: This section is possibly obsolete.
Since you use the search widget which for some reason uses different back arrow (not visually, technically) than the one included with appcompat-v7, you have to set it manually in the app's theme. Support library's drawables get tinted correctly. Otherwise it would be always white.
<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
As for the search view text...there's no easy way. After digging through its source I found a way to get to the text view. I haven't tested this so please let me know in the comments if this didn't work.
SearchView sv = ...; // get your search view instance in onCreateOptionsMenu
// prefix identifier with "android:" if you're using native SearchView
TextView tv = sv.findViewById(getResources().getIdentifier("id/search_src_text", null, null));
tv.setTextColor(Color.GREEN); // and of course specify your own color
Appropriate styling for a default action appcompat-v7 action bar would look like this:
<!-- ActionBar vs Toolbar. -->
<style name="Widget.MyApp.ActionBar.Solid" parent="Widget.AppCompat.ActionBar.Solid">
<item name="background">@color/actionbar_color</item> <!-- No prefix. -->
<item name="elevation">4dp</item> <!-- No prefix. -->
<item name="titleTextStyle">...</item> <!-- Style vs appearance. -->
</style>
<style name="Theme.MyApp" parent="Theme.AppCompat">
<item name="actionBarStyle">@style/Widget.MyApp.ActionBar.Solid</item>
<item name="actionBarTheme">@style/ThemeOverlay.MyApp.ActionBar</item>
<item name="actionBarPopupTheme">@style/ThemeOverlay.AppCompat.Light</item>
</style>
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
The accepted solution will not actually work.
You will notice that the content div
will be equal to the height of its parent, body
.
So setting the body
height to 100%
will set it equal to the height of the browser window. Let's say the browser window was 768px
in height, by setting the content div
height to 100%
, the div
's height will in turn be 768px
. Thus, you will end up with the header div being 150px
and the content div being 768px
. In the end you will have content 150px
below the bottom of the page. For another solution, check out this link.
For those of you who are now using iOS 6 or higher, UITextAlignmentCenter has been deprecated. It is now NSTextAlignmentCenter
EXAMPLE: mylabel.textAlignment = NSTextAlignmentCenter;
Works perfectly.
I've been using this line to launch the default browser:
System.Diagnostics.Process.Start("http://www.google.com");
I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)
fs.open('log.txt', 'a', function(err, log) {
if (err) throw err;
fs.writeFile(log, 'Hello Node', function (err) {
if (err) throw err;
fs.close(log, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});
You can use LINQ to DataSet/DataTable
var rows = dt.AsEnumerable()
.Where(r=> r.Field<int>("ID") == 5);
Since each row has a unique ID, you should use Single/SingleOrDefault
which would throw exception if you get multiple records back.
DataRow dr = dt.AsEnumerable()
.SingleOrDefault(r=> r.Field<int>("ID") == 5);
(Substitute int
for the type of your ID field)
Based on Kapitán Mlíko's answer with source above, I would change it to use the following:
It's a better practice to use the Marlett font rather than Path Data points for the Minimize, Restore/Maximize and Close buttons.
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25">
<TextBlock Text="0" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="3.5,0,0,3" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True">
<TextBlock Text="2" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<TextBlock Text="1" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="2,0,0,1" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25">
<TextBlock Text="r" FontFamily="Marlett" FontSize="14" VerticalAlignment="Center" HorizontalAlignment="Center" Padding="0,0,0,1" />
</Grid>
</Button.Content>
</Button>
I think this is slightly more readable. It uses Array.from
and logic is identical to using nested loops:
var arr = [_x000D_
[1, 2, 3, 4],_x000D_
[1, 2, 3, 4],_x000D_
[1, 2, 3, 4]_x000D_
];_x000D_
_x000D_
/*_x000D_
* arr[0].length = 4 = number of result rows_x000D_
* arr.length = 3 = number of result cols_x000D_
*/_x000D_
_x000D_
var result = Array.from({ length: arr[0].length }, function(x, row) {_x000D_
return Array.from({ length: arr.length }, function(x, col) {_x000D_
return arr[col][row];_x000D_
});_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
If you are dealing with arrays of unequal length you need to replace arr[0].length
with something else:
var arr = [_x000D_
[1, 2],_x000D_
[1, 2, 3],_x000D_
[1, 2, 3, 4]_x000D_
];_x000D_
_x000D_
/*_x000D_
* arr[0].length = 4 = number of result rows_x000D_
* arr.length = 3 = number of result cols_x000D_
*/_x000D_
_x000D_
var result = Array.from({ length: arr.reduce(function(max, item) { return item.length > max ? item.length : max; }, 0) }, function(x, row) {_x000D_
return Array.from({ length: arr.length }, function(x, col) {_x000D_
return arr[col][row];_x000D_
});_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
You can use wc -l
to figure out the total # of lines.
You can then combine head
and tail
to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:
tail -1562 MyHugeLogFile.log | head -838 | ....
Or there's probably an easier way using sed
or awk
.
As correct as the other answers may be, in the context that the quote was in, hashing is a tool that may be used in securing information, encryption is a process that takes information and makes it very difficult for unauthorized people to read/use.
The changelog is sloppily worded. from __future__ import absolute_import
does not care about whether something is part of the standard library, and import string
will not always give you the standard-library module with absolute imports on.
from __future__ import absolute_import
means that if you import string
, Python will always look for a top-level string
module, rather than current_package.string
. However, it does not affect the logic Python uses to decide what file is the string
module. When you do
python pkg/script.py
pkg/script.py
doesn't look like part of a package to Python. Following the normal procedures, the pkg
directory is added to the path, and all .py
files in the pkg
directory look like top-level modules. import string
finds pkg/string.py
not because it's doing a relative import, but because pkg/string.py
appears to be the top-level module string
. The fact that this isn't the standard-library string
module doesn't come up.
To run the file as part of the pkg
package, you could do
python -m pkg.script
In this case, the pkg
directory will not be added to the path. However, the current directory will be added to the path.
You can also add some boilerplate to pkg/script.py
to make Python treat it as part of the pkg
package even when run as a file:
if __name__ == '__main__' and __package__ is None:
__package__ = 'pkg'
However, this won't affect sys.path
. You'll need some additional handling to remove the pkg
directory from the path, and if pkg
's parent directory isn't on the path, you'll need to stick that on the path too.
When creating the AlertDialog
you can set a theme to use.
Example - Creating the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
styles.xml - Custom style
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">#FFC107</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">#4CAF50</item>
</style>
Result
Edit
In order to change the Appearance of the Title, you can do the following. First add a new style:
<style name="MyTitleTextStyle">
<item name="android:textColor">#FFEB3B</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>
afterwards simply reference this style in your MyAlertDialogStyle
:
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
...
<item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>
This way you can define a different textColor
for the message via android:textColorPrimary
and a different for the title via the style.
Create the reference of image....
UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];
displaying image in image view... imagedisplay is reference of imageview:
imagedisplay.image = rainyImage;
convert it into NSData
by passing UIImage
reference and provide compression quality in float values:
NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);
Just set the Environment variable to JAVA_HOME of
C:\Program Files\Java\jdk1.7.0_51)
with out bin for 64 bit version and same for 32 bit version with Program Files(x86).
NO \BIN
after the path it will work properly.
The Laravel way
Try this:
$foo = \File::extension($filename);
PyMySQL gives MySQLDb like interface as well. You could try in your initialization:
import pymysql
pymysql.install_as_MySQLdb()
Also there is a port of mysql-python on github for python3.
The purpose of this is so I can have a second version of my app which is ad supported in the app store.
Currently the best way to do it is without copying the project.
You can do it using diffent flavors in your build.gradle
file.
productFlavors {
flavor1 {
applicationId = "com.example.my.pkg.flavor1"
}
flavorAdSUpport {
applicationId = "com.example.my.pkg.flavor2"
}
}
In this way you have only a copy of the files and you can handle the difference easily.
You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.
if( !isset($_SESSION['uid']) )
die( "Login required." );
(Assuming you want to check if someone is logged in)
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
No, the URL will always be updated when params are passed to transitionTo
.
This happens on state.js:698 in ui-router.
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched
overflow-y: scroll;
to
overflow-y: auto;
Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.
xhtml below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Div in table</title>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<style type="text/css" media="all">
th {border-bottom: 2px solid #ccc; }
th,td {padding: 0.5em 1em;
margin: 0;
border-collapse: collapse;
}
tr td:first-child
{border-right: 2px solid #ccc; }
td > div {width: 249px;
height: 299px;
background-color:Gray;
overflow-y: auto;
max-width:230px;
max-height:100px;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div>
<table>
<thead>
<tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
</thead>
<tbody>
<tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
<tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
<tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
<tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
<tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
<tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
<tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
</body>
</table>
</div>
</body>
</html>
Single command without ps variables when using JSON
as body {lastName:"doe"}
for POST api call:
Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
-Method POST `
-Body (@{"lastName"="doe";}|ConvertTo-Json) `
-Uri https://api.dummy.com/getUsers `
-ContentType application/json
http://www.dreamincode.net/forums/topic/99678-j2se-vs-j2ee-what-are-main-differences/
As far as the language goes it is not as though java changes. Java EE has access to all of the SE libraries. However EE adds a set of libraries for dealing with enterprise applications.
Java EE is more like a "platform" or an general area of development.
In Java SE you write applications that run as standalone java programs or as Applets. In JavaEE you can still do this, but you can also write applications that run inside of a Java EE container. The container can do a great amount of management for you such as scaling an application across threads, providing resource pools, and management features.
Java EE has a web framework based upon Servlets. It has JSP (Java Server Pages) which is a templating language that compiles from JSP to a Java servlet where it can be run by the container.
So Java EE is more or less Java SE + Enterprise platform technologies.
Java EE is far more than just a couple of extra libraries (that is what I thought when I first looked at it) since there are a ton of frameworks and technologies built upon the Java EE specifications.
But it all boils down to just plain old java.
I needed something similar, so I wrote https://github.com/beradrian/jsbandwidth. This is a rewrite of https://code.google.com/p/jsbandwidth/.
The idea is to make two calls through Ajax, one to download and the other to upload through POST.
It should work with both jQuery.ajax
or Angular $http
.
That's an Object and you want to count the properties of it.
Object.keys(jsonArray).length
References:
I personally prefer the simpler syntax of the ~ operator.
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;
Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `
Primary key mainly prevent duplication and shows the uniqueness of columns Foreign key mainly shows relationship on two tables
This is what I use (typically for html table email reports)
declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3))
+':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2)
+':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms
You need to restart VirtualBox service you can do it with this:
sudo /Library/StartupItems/VirtualBox/VirtualBox restart
If in this path is empty you can use:
sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart
After I use Parallels I always need to do it.
If you are running the container as a service
using docker swarm
, you can do:
docker service update --env-add <you environment variable> <service_name>
Also remove using --env-rm
To make sure it's addedd as you wanted, just run:
docker exec -it <container id> env
?you should do these steps :
??simply here is the summery of those 5 steps:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}
See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola
When I turn off my Comodo Antivirus everything goes back normal. All other solutions suggested here went in vain. Somehow I figured out one solution.
If you are using Comodo Antivirus (Version 6.3/ For other versions search for similar options) the following solution would help you.
Open Comodo > Tasks > Advanced Tasks > Open Advanced Settings > Security Settings > Firewall > Firewall Settings > Advanced : Filter loopback traffic (e.g. 127.x.x.x, ::1)
Uncheck this "Filter loopback traffic" option, which prevents adb from normal working.
Sometimes you have two entities and there's a relationship between them. For example, you might have an entity called University
and another entity called Student
and a University might have many Students:
The University entity might have some basic properties such as id, name, address, etc. as well as a collection property called students that returns the list of students for a given university:
public class University {
private String id;
private String name;
private String address;
private List<Student> students;
// setters and getters
}
Now when you load a University from the database, JPA loads its id, name, and address fields for you. But you have two options for how students should be loaded:
getStudents()
method.When a university has many students it is not efficient to load all of its students together with it, especially when they are not needed and in suchlike cases you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.
Here's an example, where students
is explicitly marked to be loaded eagerly:
@Entity
public class University {
@Id
private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.EAGER)
private List<Student> students;
// etc.
}
And here's an example where students
is explicitly marked to be loaded lazily:
@Entity
public class University {
@Id
private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.LAZY)
private List<Student> students;
// etc.
}
The common way is the format()
function:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
It works fine with a multi-line format string:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
You can also pass a dictionary with variables:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
The closest thing to what you asked (in terms of syntax) are template strings. For example:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
I should add though that the format()
function is more common because it's readily available and it does not require an import line.
MVC4 has solved this problem by adding a new TextBoxFor
overload, which takes a string format parameter. You can now simply do this:
@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}")
There's also an overload that takes html attributes, so you can set the CSS class, wire up datepickers, etc:
@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}", new { @class="input-large" })
I've come across a cross-platform implementation of kbhit
at http://home.wlu.edu/~levys/software/kbhit.py (made edits to remove irrelevant code):
import os
if os.name == 'nt':
import msvcrt
else:
import sys, select
def kbhit():
''' Returns True if a keypress is waiting to be read in stdin, False otherwise.
'''
if os.name == 'nt':
return msvcrt.kbhit()
else:
dr,dw,de = select.select([sys.stdin], [], [], 0)
return dr != []
Make sure to read()
the waiting character(s) -- the function will keep returning True
until you do!
Many ways to do that in Swift:
We check the model below (we can only do a case sensitive search here):
class func isUserUsingAnIpad() -> Bool {
let deviceModel = UIDevice.currentDevice().model
let result: Bool = NSString(string: deviceModel).containsString("iPad")
return result
}
We check the model below (we can do a case sensitive/insensitive search here):
class func isUserUsingAnIpad() -> Bool {
let deviceModel = UIDevice.currentDevice().model
let deviceModelNumberOfCharacters: Int = count(deviceModel)
if deviceModel.rangeOfString("iPad",
options: NSStringCompareOptions.LiteralSearch,
range: Range<String.Index>(start: deviceModel.startIndex,
end: advance(deviceModel.startIndex, deviceModelNumberOfCharacters)),
locale: nil) != nil {
return true
} else {
return false
}
}
UIDevice.currentDevice().userInterfaceIdiom
below only returns iPad if the app is for iPad or Universal. If it is an iPhone app being ran on an iPad then it won't. So you should instead check the model. :
class func isUserUsingAnIpad() -> Bool {
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
return true
} else {
return false
}
}
This snippet below does not compile if the class does not inherit of an UIViewController
, otherwise it works just fine. Regardless UI_USER_INTERFACE_IDIOM()
only returns iPad if the app is for iPad or Universal. If it is an iPhone app being ran on an iPad then it won't. So you should instead check the model. :
class func isUserUsingAnIpad() -> Bool {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad) {
return true
} else {
return false
}
}
public class Permutation {
//display all combination attached to a 3 digit number
public static void main(String ar[]){
char data[][]= new char[][]{{'a','k','u'},
{'b','l','v'},
{'c','m','w'},
{'d','n','x'},
{'e','o','y'},
{'f','p','z'},
{'g','q','0'},
{'h','r','0'},
{'i','s','0'},
{'j','t','0'}};
int num1, num2, num3=0;
char tempdata[][]= new char[3][3];
StringBuilder number = new StringBuilder("324"); // a 3 digit number
//copy data to a tempdata array-------------------
num1= Integer.parseInt(number.substring(0,1));
tempdata[0] = data[num1];
num2= Integer.parseInt(number.substring(1,2));
tempdata[1] = data[num2];
num3= Integer.parseInt(number.substring(2,3));
tempdata[2] = data[num3];
//display all combinations--------------------
char temp2[][]=tempdata;
char tempd, tempd2;
int i,i2, i3=0;
for(i=0;i<3;i++){
tempd = temp2[0][i];
for (i2=0;i2<3;i2++){
tempd2 = temp2[1][i2];
for(i3=0;i3<3;i3++){
System.out.print(tempd);
System.out.print(tempd2);
System.out.print(temp2[2][i3]);
System.out.println();
}//for i3
}//for i2
}
}
}//end of class
Another approach is to use ForEach-Object to project individual items to a string and then use the Out-String CmdLet to project the final results to a string or string array:
gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String
#Result: One multi-line string equal to:
@"
CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0
CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d
CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b
CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426
"@
gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String -Stream
#Result: An array of single line strings equal to:
@(
"CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0",
"CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d",
"CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b",
"CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426")
The benefit of this approach is that you can store the result to a variable and it will NOT have any empty lines.
In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit).
Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using:
On git:
git revert <commit>
On mercurial:
hg backout <REV>
EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.
answers in half part of what is happening. if onOptionsItemSelected
not control homeAsUp
button when parent activity sets in manifest.xml system goes to parent activity. use like this in activity tag:
<activity ... >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.activities.MainActivity" />
</activity>
Nice and concise way is to use Lombok annotations. It has @ToString
annotation, which will generate an implementation of the toString()
method. By default, it will print your class name, along with each field, in order, separated by commas.
You can easily customize your output by passing parameters to annotation, e.g.:
@ToString(of = {"name", "lastName"})
Which is equivalent of pure Java:
public String toString() {
return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
}
A simple solution for me was to go to Properties -> Java Build Path -> Order and Export, then check the Apache Tomcat library. This is assumes you've already set Tomcat as your deployment target and are still getting the error.
Rather simpler method would be by using JavaScript method of innerHTML.
document.getElementById("#id_goes_here").innerHTML = "";
Rather simpler and more effective way.
the field=value
syntax in queries is a shorthand for field__exact=value
. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:
exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second
isnull
regex
iregex
I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter()
or exclude()
as Jason Baker suggests you'll get exactly what you need for just about any possible query.
You can also use the Package Manager Console and invoke the Install-Package
cmdlet by specifying the path to the directory that contains the package file in the -Source
parameter:
Install-Package SomePackage -Source C:\PathToThePackageDir\
The error you are getting is due to ask for a property of a null object. Your item must be null so when asking for its value to be compared you are getting that error. Check that you are getting data or your list is a list of objects and not simple strings.
According to MDN, the
split()
method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.
var str = 'Hello my friend'
var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]
var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]
console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else
Read more about Bitwise and Bit Shift Operators
>> Signed right shift
>>> Unsigned right shift
The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator >>>
shifts a zero into the leftmost position,
while the leftmost position after >>
depends on sign extension.
In simple words >>>
always shifts a zero into the leftmost position whereas >>
shifts based on sign of the number i.e. 1 for negative number and 0 for positive number.
For example try with negative as well as positive numbers.
int c = -153;
System.out.printf("%32s%n",Integer.toBinaryString(c >>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c >>>= 2));
System.out.println(Integer.toBinaryString(c <<= 2));
System.out.println();
c = 153;
System.out.printf("%32s%n",Integer.toBinaryString(c >>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c >>>= 2));
System.out.printf("%32s%n",Integer.toBinaryString(c <<= 2));
output:
11111111111111111111111111011001
11111111111111111111111101100100
111111111111111111111111011001
11111111111111111111111101100100
100110
10011000
100110
10011000
This can be achieved by the below code in Java 8 which has introduced a constructor which only takes a comparator.
PriorityQueue<Integer> maxPriorityQ = new PriorityQueue<Integer>(Collections.reverseOrder());
Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger
That is especially handy when your Bar.someMethod() is private
.
../../../includes/boot.inc.php
Imagine there is some resource like --> http://hashcodehub.com/user , now in future we are changing the resouce name to user- info --> now the url should be http://hashcodehub.com/user-info --> but the user is still trying to access the same URL --> http://hashcodehub.com/user --> here from the backend we can redirect the user to the new url and send the status code as 301 --> which is used for permanently moved.
Above I have explained how 301 Works
302 --> Temporary redirection --> here the complete url does not need to be changed but for some reason we are redirecting to resource at different locations. Here in the location header field we will give the value of the new resource url browser will again make the request to the resource url in the response location header field.
302 can be used just in case if there is something not appropriate content on our page .While we solve that issue we can redirect all our used to some temporary url and fix the issue.
It can also be used if there is some attach on the website and some pages requires restoration in that case also we can redirect the user to the different resource.
The redirect 302 serves, for example, to have several versions of a homepage in different languages.The main one can be in English; but if the visitors come from other countries then this system automatically redirects them to page in their language.
Set the timeout parameter:
r = requests.get(w, verify=False, timeout=10) # 10 seconds
As long as you don't set stream=True
on that request, this will cause the call to requests.get()
to timeout if the connection takes more than ten seconds, or if the server doesn't send data for more than ten seconds.
This worked for me:
df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]
If you need form
inside tr
and input
s in every td
, you can add form
in td
tag, and add attribute 'form' that contains id of form
tag to outside input
s.
Something like this:
<tr>
<td>
<form id='f1'>
<input type="text">
</form>
</td>
<td>
<input form='f1' type="text">
</td>
</tr>