Make sure you have closed your MSAccess file before running the java program.
Not exactly what you were asking, but you can make action a template member function:
template<typename Subclass>
class A {
public:
//Why doesn't it like this?
template<class V> void action(V var) {
(static_cast<Subclass*>(this))->do_action();
}
};
class B : public A<B> {
public:
typedef int mytype;
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv) {
B myInstance;
return 0;
}
If you are trying to do this, it means you are doing something wrong. Consider using a dict
instead.
def show_val(vals, name):
print "Name:", name, "val:", vals[name]
vals = {'a': 1, 'b': 2}
show_val(vals, 'b')
Output:
Name: b val: 2
In my case, some of my rows didn't have the same number of columns as the header. Example, Header has 10 columns, and one of your rows has 8 or 9 columns. (Columns = Count number of you delimiter characters in each line)
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
This might be your problem:
height: .05em;
Chrome is a bit funky with decimals, so try a fixed-pixel height:
height: 2px;
I wrote a useful method to call any action that takes a StreamWriter
and write it out to a string instead. The method is like this;
static void SendStreamToString(Action<StreamWriter> action, out string destination)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream, Encoding.Unicode))
{
action(writer);
writer.Flush();
stream.Position = 0;
destination = Encoding.Unicode.GetString(stream.GetBuffer(), 0, (int)stream.Length);
}
}
And you can use it like this;
string myString;
SendStreamToString(writer =>
{
var ints = new List<int> {1, 2, 3};
writer.WriteLine("My ints");
foreach (var integer in ints)
{
writer.WriteLine(integer);
}
}, out myString);
I know this can be done much easier with a StringBuilder
, the point is that you can call any method that takes a StreamWriter
.
Meaning, AF_INET
refers to addresses from the internet, IP addresses specifically. PF_INET
refers to anything in the protocol, usually sockets/ports.
Consider reading the man pages for socket(2) and bind(2). For the sin_addr
field, just do something like the following to set it:
struct sockaddr_in addr;
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
add delim_whitespace=True
argument, it's faster than regex.
String[] strarray = strlist.toArray(new String[0]);
if u want List convert to string use StringUtils.join(slist, '\n');
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
Nothing seemd to work for me, but this did the trick
$(parent.window.document).scroll(function() {
alert("bottom!");
});
To supply an example of why it has to be a string:
If you format 1.toFixed(2) you would get '1.00'.
This is not the same as 1, as 1 does not have 2 decimals.
I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like: roundedValue = Math.round(value * 100) * 0.01
The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.
You'll get the error with (for instance):
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
You won't with:
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">
Notice ""
at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.
By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.
The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).
In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.
This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)
Your problem seams to be located here:
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,LEN(Voucher_No)- LEN(@Prefix)) AS INT)) AS varchar(100)) FROM dbo.Journal_Entry;
SET @sCode=CAST(@maxCode AS INT)
As the error says, you're casting a string that contains a letter 'J' to an INT
which for obvious reasons is not possible.
Either fix SUBSTRING
or don't store the letter 'J' in the database and only prepend it when reading.
Use split
and map
function:
var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });
Notice +val
- string is casted to a number.
Or shorter:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });
Today I'd advise against using +
operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number
call:
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
return Number(val) + 1;_x000D_
});_x000D_
console.log(arr);
_x000D_
ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_
console.log(arr);
_x000D_
#include <stdio.h>
#include "opencv.hpp"
int main(){
CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
if (camera==NULL)
printf("camera is null\n");
else
printf("camera is not null");
cvNamedWindow("img");
while (cvWaitKey(10)!=atoi("q")){
double t1=(double)cvGetTickCount();
IplImage *img=cvQueryFrame(camera);
double t2=(double)cvGetTickCount();
printf("time: %gms fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
cvShowImage("img",img);
}
cvReleaseCapture(&camera);
}
Sometimes you get the error because the destination location in phone are not exist. For example, some android phone external storage location is /storage/emulated/legacy
instead of /storage/emulated/0
.
This one interested me, and I finally had a chance to look into it. Other folks apparently haven't understood that this is an issue with finding the view, not an issue with the routing itself - and that's probably because your question title indicates that it's about routing.
In any case, because this is a View-related issue, the only way to get what you want is to override the default view engine. Normally, when you do this, it's for the simple purpose of switching your view engine (i.e. to Spark, NHaml, etc.). In this case, it's not the View-creation logic we need to override, but the FindPartialView
and FindView
methods in the VirtualPathProviderViewEngine
class.
You can thank your lucky stars that these methods are in fact virtual, because everything else in the VirtualPathProviderViewEngine
is not even accessible - it's private, and that makes it very annoying to override the find logic because you have to basically rewrite half of the code that's already been written if you want it to play nice with the location cache and the location formats. After some digging in Reflector I finally managed to come up with a working solution.
What I've done here is to first create an abstract AreaAwareViewEngine
that derives directly from VirtualPathProviderViewEngine
instead of WebFormViewEngine
. I did this so that if you want to create Spark views instead (or whatever), you can still use this class as the base type.
The code below is pretty long-winded, so to give you a quick summary of what it actually does: It lets you put a {2}
into the location format, which corresponds to the area name, the same way {1}
corresponds to the controller name. That's it! That's what we had to write all this code for:
public abstract class BaseAreaAwareViewEngine : VirtualPathProviderViewEngine
{
private static readonly string[] EmptyLocations = { };
public override ViewEngineResult FindView(
ControllerContext controllerContext, string viewName,
string masterName, bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentNullException(viewName,
"Value cannot be null or empty.");
}
string area = getArea(controllerContext);
return FindAreaView(controllerContext, area, viewName,
masterName, useCache);
}
public override ViewEngineResult FindPartialView(
ControllerContext controllerContext, string partialViewName,
bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(partialViewName))
{
throw new ArgumentNullException(partialViewName,
"Value cannot be null or empty.");
}
string area = getArea(controllerContext);
return FindAreaPartialView(controllerContext, area,
partialViewName, useCache);
}
protected virtual ViewEngineResult FindAreaView(
ControllerContext controllerContext, string areaName, string viewName,
string masterName, bool useCache)
{
string controllerName =
controllerContext.RouteData.GetRequiredString("controller");
string[] searchedViewPaths;
string viewPath = GetPath(controllerContext, ViewLocationFormats,
"ViewLocationFormats", viewName, controllerName, areaName, "View",
useCache, out searchedViewPaths);
string[] searchedMasterPaths;
string masterPath = GetPath(controllerContext, MasterLocationFormats,
"MasterLocationFormats", masterName, controllerName, areaName,
"Master", useCache, out searchedMasterPaths);
if (!string.IsNullOrEmpty(viewPath) &&
(!string.IsNullOrEmpty(masterPath) ||
string.IsNullOrEmpty(masterName)))
{
return new ViewEngineResult(CreateView(controllerContext, viewPath,
masterPath), this);
}
return new ViewEngineResult(
searchedViewPaths.Union<string>(searchedMasterPaths));
}
protected virtual ViewEngineResult FindAreaPartialView(
ControllerContext controllerContext, string areaName,
string viewName, bool useCache)
{
string controllerName =
controllerContext.RouteData.GetRequiredString("controller");
string[] searchedViewPaths;
string partialViewPath = GetPath(controllerContext,
ViewLocationFormats, "PartialViewLocationFormats", viewName,
controllerName, areaName, "Partial", useCache,
out searchedViewPaths);
if (!string.IsNullOrEmpty(partialViewPath))
{
return new ViewEngineResult(CreatePartialView(controllerContext,
partialViewPath), this);
}
return new ViewEngineResult(searchedViewPaths);
}
protected string CreateCacheKey(string prefix, string name,
string controller, string area)
{
return string.Format(CultureInfo.InvariantCulture,
":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:",
base.GetType().AssemblyQualifiedName,
prefix, name, controller, area);
}
protected string GetPath(ControllerContext controllerContext,
string[] locations, string locationsPropertyName, string name,
string controllerName, string areaName, string cacheKeyPrefix,
bool useCache, out string[] searchedLocations)
{
searchedLocations = EmptyLocations;
if (string.IsNullOrEmpty(name))
{
return string.Empty;
}
if ((locations == null) || (locations.Length == 0))
{
throw new InvalidOperationException(string.Format("The property " +
"'{0}' cannot be null or empty.", locationsPropertyName));
}
bool isSpecificPath = IsSpecificPath(name);
string key = CreateCacheKey(cacheKeyPrefix, name,
isSpecificPath ? string.Empty : controllerName,
isSpecificPath ? string.Empty : areaName);
if (useCache)
{
string viewLocation = ViewLocationCache.GetViewLocation(
controllerContext.HttpContext, key);
if (viewLocation != null)
{
return viewLocation;
}
}
if (!isSpecificPath)
{
return GetPathFromGeneralName(controllerContext, locations, name,
controllerName, areaName, key, ref searchedLocations);
}
return GetPathFromSpecificName(controllerContext, name, key,
ref searchedLocations);
}
protected string GetPathFromGeneralName(ControllerContext controllerContext,
string[] locations, string name, string controllerName,
string areaName, string cacheKey, ref string[] searchedLocations)
{
string virtualPath = string.Empty;
searchedLocations = new string[locations.Length];
for (int i = 0; i < locations.Length; i++)
{
if (string.IsNullOrEmpty(areaName) && locations[i].Contains("{2}"))
{
continue;
}
string testPath = string.Format(CultureInfo.InvariantCulture,
locations[i], name, controllerName, areaName);
if (FileExists(controllerContext, testPath))
{
searchedLocations = EmptyLocations;
virtualPath = testPath;
ViewLocationCache.InsertViewLocation(
controllerContext.HttpContext, cacheKey, virtualPath);
return virtualPath;
}
searchedLocations[i] = testPath;
}
return virtualPath;
}
protected string GetPathFromSpecificName(
ControllerContext controllerContext, string name, string cacheKey,
ref string[] searchedLocations)
{
string virtualPath = name;
if (!FileExists(controllerContext, name))
{
virtualPath = string.Empty;
searchedLocations = new string[] { name };
}
ViewLocationCache.InsertViewLocation(controllerContext.HttpContext,
cacheKey, virtualPath);
return virtualPath;
}
protected string getArea(ControllerContext controllerContext)
{
// First try to get area from a RouteValue override, like one specified in the Defaults arg to a Route.
object areaO;
controllerContext.RouteData.Values.TryGetValue("area", out areaO);
// If not specified, try to get it from the Controller's namespace
if (areaO != null)
return (string)areaO;
string namespa = controllerContext.Controller.GetType().Namespace;
int areaStart = namespa.IndexOf("Areas.");
if (areaStart == -1)
return null;
areaStart += 6;
int areaEnd = namespa.IndexOf('.', areaStart + 1);
string area = namespa.Substring(areaStart, areaEnd - areaStart);
return area;
}
protected static bool IsSpecificPath(string name)
{
char ch = name[0];
if (ch != '~')
{
return (ch == '/');
}
return true;
}
}
Now as stated, this isn't a concrete engine, so you have to create that as well. This part, fortunately, is much easier, all we need to do is set the default formats and actually create the views:
public class AreaAwareViewEngine : BaseAreaAwareViewEngine
{
public AreaAwareViewEngine()
{
MasterLocationFormats = new string[]
{
"~/Areas/{2}/Views/{1}/{0}.master",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.master",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Views/{1}/{0}.master",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.master"
"~/Views/Shared/{0}.cshtml"
};
ViewLocationFormats = new string[]
{
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.aspx"
"~/Views/Shared/{0}.ascx"
"~/Views/Shared/{0}.cshtml"
};
PartialViewLocationFormats = ViewLocationFormats;
}
protected override IView CreatePartialView(
ControllerContext controllerContext, string partialPath)
{
if (partialPath.EndsWith(".cshtml"))
return new System.Web.Mvc.RazorView(controllerContext, partialPath, null, false, null);
else
return new WebFormView(controllerContext, partialPath);
}
protected override IView CreateView(ControllerContext controllerContext,
string viewPath, string masterPath)
{
if (viewPath.EndsWith(".cshtml"))
return new RazorView(controllerContext, viewPath, masterPath, false, null);
else
return new WebFormView(controllerContext, viewPath, masterPath);
}
}
Note that we've added few entries to the standard ViewLocationFormats
. These are the new {2}
entries, where the {2}
will be mapped to the area
we put in the RouteData
. I've left the MasterLocationFormats
alone, but obviously you can change that if you want.
Now modify your global.asax
to register this view engine:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaAwareViewEngine());
}
...and register the default route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Area",
"",
new { area = "AreaZ", controller = "Default", action = "ActionY" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
Now Create the AreaController
we just referenced:
public class DefaultController : Controller
{
public ActionResult ActionY()
{
return View("TestView");
}
}
Obviously we need the directory structure and view to go with it - we'll keep this super simple:
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<h2>TestView</h2>
This is a test view in AreaZ.
And that's it. Finally, we're done.
For the most part, you should be able to just take the BaseAreaAwareViewEngine
and AreaAwareViewEngine
and drop it into any MVC project, so even though it took a lot of code to get this done, you only have to write it once. After that, it's just a matter of editing a few lines in global.asax.cs
and creating your site structure.
New location for mysql config file is
/etc/mysql/mysql.conf.d/mysqld.cnf
IIS will create it again AFAIK.
The solution provided by ebeneditos works perfectly.
But if you have cv2.imwrite()
in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite()
individually.
As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)
Now if you want to modify the path, you just have to change the path
variable.
Edited based on solution provided by Kallz
Some posts have showed how to display the command's progress. In order to calculate it, you'll need to see how much you've progressed. On BSD systems some commands, such as dd(1), accept a SIGINFO
signal, and will report their progress. On Linux systems some commands will respond similarly to SIGUSR1
. If this facility is available, you can pipe your input through dd
to monitor the number of bytes processed.
Alternatively, you can use lsof
to obtain the offset of the file's read pointer, and thereby calculate the progress. I've written a command, named pmonitor, that displays the progress of processing a specified process or file. With it you can do things, such as the following.
$ pmonitor -c gzip
/home/dds/data/mysql-2015-04-01.sql.gz 58.06%
An earlier version of Linux and FreeBSD shell scripts appears on my blog.
Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame
Windows are just normal WPF application Windows, but can host Pages via a Frame container
What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:
if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }
if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
&& $string !~ /Bush/i) {
print "$string\n"
}
official Link of DB 2 JDBC Driver from IBM
ULs don't have a name attribute, but you can reference the ul by tag name.
Try replacing line 3 in your script with this:
var sub = cat.getElementsByTagName("UL");
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
The abstract version can be:
import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList = np.divide(myList, myInt)
Here the Kotlin version of Arth Tilvas answer:
fun getMacAddr(): String {
try {
val all = Collections.list(NetworkInterface.getNetworkInterfaces())
for (nif in all) {
if (!nif.getName().equals("wlan0", ignoreCase=true)) continue
val macBytes = nif.getHardwareAddress() ?: return ""
val res1 = StringBuilder()
for (b in macBytes) {
//res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:", b))
}
if (res1.length > 0) {
res1.deleteCharAt(res1.length - 1)
}
return res1.toString()
}
} catch (ex: Exception) {
}
return "02:00:00:00:00:00"
}
Any positive integer, excluding 0: ^\+?[1-9]\d*$
Any positive integer, including 0: ^(0|\+?[1-9]\d*)$
Since XML is a text format and images are usually not (except some ancient and archaic formats) there is no really sensible way to do it. Looking at things like ODT or OOXML also shows you that they don't embed images directly into XML.
What you can do, however, is convert it to Base64 or similar and embed it into the XML.
XML's whitespace handling may further complicate things in such cases, though.
You must to set by this order:
<link rel="stylesheet" href="path/bootstrap.min.css">
<style type="text/css">
@font-face { font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
url('../fonts/glyphicons-halflings-regular.woff') format('woff'),
url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),
url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg'); }
</style>
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
Use the -ExpandProperty
flag of Select-Object
$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority
Update to answer the other question:
Note that you can as well just access the property:
$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
So to get multiple of these into variables:
$var=Get-WSManInstance -enumerate wmicimv2/win32_process
$prio = $var.Priority
$pid = $var.ProcessID
function saveProfile(){
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$post_data = array('firstname'=> $firstname,'lastname'=>$lastname);
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
Use a js library like underscore.js for these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
Use string
instead of string?
in all places in your code.
The Nullable<T>
type requires that T is a non-nullable value type, for example int
or DateTime
. Reference types like string
can already be null. There would be no point in allowing things like Nullable<string>
so it is disallowed.
Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:
public class WordAndMeaning
{
public string Word { get; set; }
public string Meaning { get; set; }
}
You need to use the .format()
function.
MM
- Month number
MMM
- Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
the @require meta does not work when you want to unbind events on a webpage using jQuery, you have to use a jQuery library included in the webpage and then get it in Greasemonkey with var $ = unsafeWindow.jQuery;
How do I unbind jquery event handlers in greasemonkey?
This works for setting the value of the INPUT:
strftime('%Y-%m-%dT%H:%M:%S', time())
You're getting final 0
because your while loop
is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.
Correct script:
while read -r country _; do
if [ "US" = "$country" ]; then
((USCOUNTER++))
echo "US counter $USCOUNTER"
fi
done < "$FILE"
You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]
Note: for option 4 for you'll need to import numpy as np
Update: You can also use the .query
method for this too. This allows for method chaining:
5. df.query("column not in @values")
.
where values
is a list of the values that you don't want to include.
Well, this solution will help you select only current month, current week and only today
SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;
For Weekly added posts:
WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())
For Monthly added posts:
MONTH(addedon_gm) = MONTH(NOW())
For Yearly added posts:
YEAR(addedon_gm) = YEAR(NOW())
you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.
$original_str="this . is . to . find";
echo "<br/> Position: ". $pos=strrpos($original_str, ".");
$len=strlen($original_str);
if($pos >= 0)
{
echo "<br/> Extension: ". substr($original_str,$pos+1,$len-$pos) ;
}
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
We can also use logging to print data on the console.
Example:
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
without considering this to be a good idea...
select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))
Function
-- Author: bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50))
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int
Select @i=CHARINDEX('.',@NumStr)
if @i=0
begin
set @i=LEN(@NumStr)
Set @Outstr=''
end
else
begin
Set @Outstr=SUBSTRING(@NUmStr,@i,50)
Set @i=@i -1
end
Set @run=0
While @i>0
begin
if @Run=3
begin
Set @Outstr=','+@Outstr
Set @run=0
end
Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr
Set @i=@i-1
Set @run=@run + 1
end
RETURN @OutStr
END
GO
One more for loop variant, looks cleaner to me than one with enumerate():
for idx in range(len(list)):
list[idx]=... # set a new value
# some other code which doesn't let you use a list comprehension
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
I had a similar issue. The root cause was that the sending IP was not in the range of white-listed IPs on the receiving server. So, all requests for communication were killed by the receiving site.
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve
saves the file to a temporary file and returns a tuple (filename, headers)
urlopen
returns a Request
object whose read
method returns a bytestring containing the file contentsI am using in the way and it is working for me.
public static void main(String[] args) {
new CarpoolDBAppTest();
}
public CarpoolDBAppTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Student stud = (Student) context.getBean("yourBeanId");
}
Here Student is my classm you will get the class matching yourBeanId.
Now work on that object with whatever operation you want to do.
Do you want coordinates relative to the screen or the application?
If it's within the application just use:
Mouse.GetPosition(Application.Current.MainWindow);
If not, I believe you can add a reference to System.Windows.Forms
and use:
System.Windows.Forms.Control.MousePosition;
Well, I don't understand why are you used transaction in case when you make a select
.
Transaction is useful when you make changes (add, edit or delete) data from database.
Remove transaction unless you use insert
, update
or delete
statements
From this version, you can use native Node.js function from util library.
const fs = require('fs')
const { promisify } = require('util')
const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)
const run = async () => {
const res = await readFileAsync('./data.json')
console.log(res)
}
run()
const fs = require('fs')
const readFile = (path, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.readFile(path, opts, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
const writeFile = (path, data, opts = 'utf8') =>
new Promise((resolve, reject) => {
fs.writeFile(path, data, opts, (err) => {
if (err) reject(err)
else resolve()
})
})
module.exports = {
readFile,
writeFile
}
...
// in some file, with imported functions above
// in async block
const run = async () => {
const res = await readFile('./data.json')
console.log(res)
}
run()
Always use try..catch
for await blocks, if you don't want to rethrow exception upper.
For those who reached this post for Answer:
This happens mainly because the InputStream
the DOM parser is consuming is empty
So in what I ran across, there might be two situations:
InputStream
you passed into the parser has been used and thus emptied.File
or whatever you created the InputStream
from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream
.What's not mentioned here is that option 1 allows you arbitrarily deep nesting of lists.
This shouldn't matter if you control the content/css, but if you're making a rich text editor it comes in handy.
For example, gmail, inbox, and evernote all allow creating lists like this:
With option 2 you cannot due that (you'll have an extra list item), with option 1, you can.
Lists both local and remote branches:
$ git branch -ra
Output:
feature/feature1
feature/feature2
hotfix/hotfix1
* master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/master
You're looking for isNaN()
:
console.log(!isNaN(123));_x000D_
console.log(!isNaN(-1.23));_x000D_
console.log(!isNaN(5-2));_x000D_
console.log(!isNaN(0));_x000D_
console.log(!isNaN("0"));_x000D_
console.log(!isNaN("2"));_x000D_
console.log(!isNaN("Hello"));_x000D_
console.log(!isNaN("2005/12/12"));
_x000D_
See JavaScript isNaN() Function at MDN.
Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.
Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController
.
It is worth quoting the documentation's warning and advice about creating unnecessary alerts.
Notes:
UIAlertView
was deprecated. You should use UIAlertController
to create alerts now.Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController
is used to make an action sheet. Before iOS 8, UIActionSheet
was used, but now the documentation says:
Important:
UIActionSheet
is deprecated in iOS 8. (Note thatUIActionSheetDelegate
is also deprecated.) To create and manage action sheets in iOS 8 and later, instead useUIAlertController
with apreferredStyle
ofUIAlertControllerStyleActionSheet
.
A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController
with one of the Modal Presentation Styles.
See also
A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController
. (Before iOS 8, UIPopoverController
was the recommended method.)
In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).
See also
Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.
See also
In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.
People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:
UIView
However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.
If you set a static height for your header, you can use that in a calculation for the size of your wrapper.
http://jsfiddle.net/ske5Lqyv/5/
Using your example code, you can add this CSS:
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
height: 100%;
}
.header {
height: 64px;
background-color: lightblue;
}
.wrapper {
height: calc(100% - 64px);
overflow-y: auto;
}
Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/
<div id="container">
<div class="section">
<div class="header">Heading</div>
<div class="wrapper">
<p>Large Text</p>
</div>
</div>
</div>
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
display: flex;
flex-direction: column;
height: 100%;
}
.section {
flex-grow: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.header {
height: 64px;
background-color: lightblue;
flex-shrink: 0;
}
.wrapper {
flex-grow: 1;
overflow: auto;
min-height: 100%;
}
And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083
For int64_t
type:
#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);
for uint64_t
type:
#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);
you can also use PRIx64
to print in hexadecimal.
cppreference.com has a full listing of available macros for all types including intptr_t
(PRIxPTR
). There are separate macros for scanf, like SCNd64
.
A typical definition of PRIu16 would be "hu"
, so implicit string-constant concatenation happens at compile time.
For your code to be fully portable, you must use PRId32
and so on for printing int32_t
, and "%d"
or similar for printing int
.
Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile
export PYTHONPATH=/path/to/dir:$PYTHONPATH
my directory is now on the pythonpath -
my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...
and I can import modules from that directory.
It seems many indie developers like me are desperately looking for an answer to these questions for years. Strangely, even after 5 years this question was asked, it seems the answer to this question is still not clear.
As far as I can see, there is not any official statement in Google AdMob
documentation or website about how a developer can safely answer these questions. It seems developers are left on their own in the mystery about answering some legally binding questions about the SDK
.
In their support forums they can advice questioners to reach out to Apple Support:
Hi there,
I believe it would be best for you to reach out to Apple Support for your concern as it tackles with Apple Submission Guidelines rather than our SDK.
Regards, Joshua Lagonera Mobile Ads SDK Team
Or they can say that it is out of their scope of support:
Hello Robert,
On this forum, we deal with Mobile Ads SDK related technical concerns only. We would not be able to address you question as this is out of scope for our team.
Regards, Deepika Uragayala Mobile Ads SDK Team
The only answer I could find from a "Google person" is about the 4th question. It is not in the AdMob forum but in the "Tag Manager" forum but still related. It is like so:
Hi Jorn,
Apple asks you about your use of IDFA when submitting your application (https://developer.apple.com/Library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html). For an app that doesn't display advertising, but includes the AdSupport framework for conversion attribution, you would select the appropriate checkbox(es). In respect to the Limit Ad Tracking stipulation, all of GTM's tags that utilize IDFA respect the limit ad tracking stipulations of the SDK.
Thanks,
Eric Burley Google Tag Manager.
Here is an Internet Archive link in case they remove this page.
Lastly, let me mention about AdMob's only statement I've seen about this issue (here is the Internet Archive link):
The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.
In conclusion, it seems most developers using AdMob simply checks 1st and 4th checkmarks and submit their apps without being completely sure about what Google exactly does in its SDK and without any official information about it. I wish good luck to us all.
If you don't need to change something onMeasure - there's absolutely no need for you to override it.
Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).
You can check the onMeasure method here :
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
Overriding SDK code to be replaced with the exact same code makes no sense.
This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.
Assuming df
is your dataframe,
df_prime = pd.concat([df, pd.DataFrame([[np.nan] * df.shape[1]], columns=df.columns)], ignore_index=True)
where df_prime
equals df
with an additional last row of NaN's.
Note that pd.concat
is slow so if you need this functionality in a loop, it's best to avoid using it.
In that case, assuming your index is incremental, you can use
df.loc[df.iloc[-1].name + 1,:] = np.nan
Clustered Index: Primary Key constraint creates clustered Index automatically if no clustered Index already exists on the table. Actual data of clustered index can be stored at leaf level of Index.
Non Clustered Index: Actual data of non clustered index is not directly found at leaf node, instead it has to take an additional step to find because it has only values of row locators pointing towards actual data. Non clustered Index can't be sorted as clustered index. There can be multiple non clustered indexes per table, actually it depends on the sql server version we are using. Basically Sql server 2005 allows 249 Non Clustered Indexes and for above versions like 2008, 2016 it allows 999 Non Clustered Indexes per table.
A solution using pathlib.Path
, which is independent of the OS used:
import zipfile
from pathlib import Path
def zip_dir(path: Path, zip_file_path: Path):
"""Zip all contents of path to zip_file"""
files_to_zip = [
file for file in path.glob('*') if file.is_file()]
with zipfile.ZipFile(
zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zip_f:
for file in files_to_zip:
print(file.name)
zip_f.write(file, file.name)
current_dir = Path.cwd()
zip_dir = current_dir / "test"
tools.zip_dir(
zip_dir, current_dir / 'Zipped_dir.zip')
If you're using C# 3.0 you can use linq, way better and way more elegant:
List<int> myList = GetListOfIntsFromSomewhere();
// This will filter out the list of ints that are > than 7, Where returns an
// IEnumerable<T> so a call to ToList is required to convert back to a List<T>.
List<int> filteredList = myList.Where( x => x > 7).ToList();
If you can't find the .Where
, that means you need to import using System.Linq;
at the top of your file.
You can use css like below;
<a href="contact.html" style="margin:auto; text-align:center; display:block;" class="button large hpbottom">Get Started</a>
The accepted answer didn't actually tell how to get the location, so here is a little more detail. You pass in an int
array of length 2 and the values are replaced with the view's (x, y) coordinates (of the top, left corner).
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Notes
getLocationOnScreen
with getLocationInWindow
should give the same results in most cases (see this answer). However, if you are in a smaller window like a Dialog or custom keyboard, then use you will need to choose which one better suits your needs.(0,0)
if you call this method in onCreate
because the view has not been laid out yet. You can use a ViewTreeObserver
to listen for when the layout is done and you can get the measured coordinates. (See this answer.)Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters
You can use the FromStr
trait's from_str
method, which is implemented for i32
:
let my_num = i32::from_str("9").unwrap_or(0);
You have to close the reader on top of your else condition.
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
Here's an easy way, albeit not the prettiest way to get an int value for a string.
hour=`expr $hour + 0`
Example
bash-3.2$ hour="08"
bash-3.2$ hour=`expr $hour + 0`
bash-3.2$ echo $hour
8
If you are running Delphi, or other native compiled CGI, this solution will work:
As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.
If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.
Click OK
The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.
In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.
Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).
The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.
For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.
There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W
is large) or the number of data points N
is very low.
To answer your original question, here's how you do it with sed:
sed -i '1icolumn1, column2, column3' testfile.csv
The "1i" command tells sed to go to line 1 and insert the text there.
The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example
sed -i~ '1icolumn1, column2, column3' testfile.csv
would keep the original file in "testfile.csv~".
You can use the get() on each dict. Make sure that you have added the None check for each access.
Use window.URL
:
> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}
or you could wrap in foreach loop to print each value
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
foreach(XmlNode curr in n) {
Console.WriteLine(curr.InnerText);
}
}
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
check collection data:-
var collections = db.getCollectionNames();_x000D_
_x000D_
for(var i = 0; i< collections.length; i++)_x000D_
{ _x000D_
print('Collection: ' + collections[i]);_x000D_
// print the name of each collection_x000D_
_x000D_
db.getCollection(collections[i]).find().forEach(printjson);_x000D_
_x000D_
//and then print the json of each of its elements_x000D_
}
_x000D_
To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)
import os, shutil
root_src_dir = r'C:\MyMusic' #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp' #Path to the destination folder
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.
maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik
With iOS7 you can simply change tintColor of the textField
If you have one large dataframe and only a few update values I would use apply like this:
import pandas as pd
df = pd.DataFrame({'filename' : ['test0.dat', 'test2.dat'],
'm': [12, 13], 'n' : [None, None]})
data = {'filename' : 'test2.dat', 'n':16}
def update_vals(row, data=data):
if row.filename == data['filename']:
row.n = data['n']
return row
df.apply(update_vals, axis=1)
Make sure that you have permissions to run the following commands.
If you check the man page of nginx from a terminal
man nginx
you can find this:
-V Print the nginx version, compiler version, and configure script parameters.
-v Print the nginx version.
Then type in terminal
nginx -v
nginx version: nginx/1.14.0
nginx -V
nginx version: nginx/1.14.0
built with OpenSSL 1.1.0g 2 Nov 2017
TLS SNI support enabled
If nginx is not installed in your system man nginx
command can not find man page, so make sure you have installed nginx.
You can also find the version using this command:
Use one of the command to find the path of nginx
ps aux | grep nginx
ps -ef | grep nginx
root 883 0.0 0.3 44524 3388 ? Ss Dec07 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
Then run from terminal:
/usr/sbin/nginx -v
nginx version: nginx/1.14.0
We had the same issue when we had a typo in the mybatis mapping file like
....
#{column1Name, jdbcType=INTEGER},
#{column2Name, jdbcType=VARCHAR},
#{column3Name, jdbcTyep=VARCHAR} -- do you see the typo ?
.....
So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.
Building up on @peeol's excellent answer, you can also remove the frame by doing
for spine in plt.gca().spines.values():
spine.set_visible(False)
To give an example (the entire code sample can be found at the end of this post), let's say you have a bar plot like this,
you can remove the frame with the commands above and then either keep the x-
and ytick
labels (plot not shown) or remove them as well doing
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
In this case, one can then label the bars directly; the final plot could look like this (code can be found below):
Here is the entire code that is necessary to generate the plots:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
xvals = list('ABCDE')
yvals = np.array(range(1, 6))
position = np.arange(len(xvals))
mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)
plt.title('My great data')
# plt.show()
# get rid of the frame
for spine in plt.gca().spines.values():
spine.set_visible(False)
# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
# plt.show()
# direct label each bar with Y axis values
for bari in mybars:
height = bari.get_height()
plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
ha='center', color='white', fontsize=15)
plt.show()
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
Great explanation here:
https://www.cuelogic.com/blog/using-framelayout-for-designing-xml-layouts-in-android
LinearLayout arranges elements side by side either horizontally or vertically.
RelativeLayout helps you arrange your UI elements based on specific rules. You can specify rules like: align this to parent’s left edge, place this to the left/right of this elements etc.
AbsoluteLayout is for absolute positioning i.e. you can specify exact co-ordinates where the view should go.
FrameLayout allows placements of views along Z-axis. That means that you can stack your view elements one above the other.
Try
select * from dataset
where id = 2
order by date limit 1
Been a while since I did sql, so this might need some tweaking.
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.
Here is an example with a Django view ...
def homepage(request):
request.session.setdefault('how_many_visits', 0)
request.session['how_many_visits'] += 1
print(request.session['how_many_visits'])
return render(request, 'home.html', {})
If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.
I solved the same problem. I've just added JSTL-1.2.jar to /apache-tomcat-x.x.x/lib
and set scope to provided in maven pom.xml:
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.
Some reasons why this might happen:
If the problem is related to timeout settings, you may be able to resolve it by investigating the following:
first of all,
be sure that there is a post
if(isset($_POST['username'])) {
// check if the username has been set
}
second, and most importantly, sanitize the data, meaning that
$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
is deadly dangerous, instead use
$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";
and please research the subject sql injection
Sometimes, pprint()
in pprint
module works wonder, especially for dict
variables.
There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.
There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.
%find . -type f | wc -l
791887
%time git add .
git add . 6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status 0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G .
%cd .git
%du -sh .
7.9G .
If it is on Github, Navigate to bitbucket and use "import repository" method to import your github repo as a private repo.
If it is in bitbucket, Do the otherway around.
It's a full backup but stays in the cloud which is my ideal method.
In .NET Core 2.0
MVC app / Microsoft.AspNetCore.All
v2.0.0, you can have environmental specific startup class as described by @vaindil but I don't like that approach.
You can also inject IHostingEnvironment
into StartUp
constructor. You don't need to store the environment variable in Program
class.
public class Startup
{
private readonly IHostingEnvironment _currentEnvironment;
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
_currentEnvironment = env;
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
......
services.AddMvc(config =>
{
// Requiring authenticated users on the site globally
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
// Validate anti-forgery token globally
config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
// If it's Production, enable HTTPS
if (_currentEnvironment.IsProduction()) // <------
{
config.Filters.Add(new RequireHttpsAttribute());
}
});
......
}
}
someMethod.func_code.co_argcount
or, if the current function name is undetermined:
import sys
sys._getframe().func_code.co_argcount
Here's a very simple Javascript example using jQuery:
function logout(to_url) {
var out = window.location.href.replace(/:\/\//, '://log:out@');
jQuery.get(out).error(function() {
window.location = to_url;
});
}
This log user out without showing him the browser log-in box again, then redirect him to a logged out page
If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:
PHP:
header('Access-Control-Allow-Origin: *');
For example, in Drupal's xmlrpc.php code you would do this:
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
If Your .htaccess have anything like this
AddType application/x-httpd-ea-php56 .php .php5 .phtm .html .htm
If you have multiples docker containers launched, use this
$ docker rm $(docker ps -aq)
It will remove all the current dockers listed in the "ps -aq" command.
Source : aaam on https://github.com/docker/docker/issues/12487
If you are trying to recursively delete directory a
and directory a\b
is open in Explorer, b
will be deleted but you will get the error 'directory is not empty' for a
even though it is empty when you go and look. The current directory of any application (including Explorer) retains a handle to the directory. When you call Directory.Delete(true)
, it deletes from bottom up: b
, then a
. If b
is open in Explorer, Explorer will detect the deletion of b
, change directory upwards cd ..
and clean up open handles. Since the file system operates asynchronously, the Directory.Delete
operation fails due to conflicts with Explorer.
I originally posted the following solution, with the idea of interrupting the current thread to allow Explorer time to release the directory handle.
// incomplete!
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Thread.Sleep(0);
Directory.Delete(path, true);
}
But this only works if the open directory is the immediate child of the directory you are deleting. If a\b\c\d
is open in Explorer and you use this on a
, this technique will fail after deleting d
and c
.
This method will handle deletion of a deep directory structure even if one of the lower-level directories is open in Explorer.
/// <summary>
/// Depth-first recursive delete, with handling for descendant
/// directories open in Windows Explorer.
/// </summary>
public static void DeleteDirectory(string path)
{
foreach (string directory in Directory.GetDirectories(path))
{
DeleteDirectory(directory);
}
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Directory.Delete(path, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(path, true);
}
}
Despite the extra work of recursing on our own, we still have to handle the UnauthorizedAccessException
that can occur along the way. It's not clear whether the first deletion attempt is paving the way for the second, successful one, or if it's merely the timing delay introduced by the throwing/catching an exception that allows the file system to catch up.
You might be able to reduce the number of exceptions thrown and caught under typical conditions by adding a Thread.Sleep(0)
at the beginning of the try
block. Additionally, there is a risk that under heavy system load, you could fly through both of the Directory.Delete
attempts and fail. Consider this solution a starting point for more robust recursive deletion.
This solution only addresses the peculiarities of interacting with Windows Explorer. If you want a rock-solid delete operation, one thing to keep in mind is that anything (virus scanner, whatever) could have an open handle to what you are trying to delete, at any time. So you have to try again later. How much later, and how many times you try, depends on how important it is that the object be deleted. As MSDN indicates,
Robust file iteration code must take into account many complexities of the file system.
This innocent statement, supplied with only a link to the NTFS reference documentation, ought to make your hairs stand up.
(Edit: A lot. This answer originally only had the first, incomplete solution.)
The explanation for how it works:
JUnit wraps your test method in a Statement object so statement and Execute()
runs your test. Then instead of calling statement.Execute()
directly to run your test, JUnit passes the Statement to a TestRule with the @Rule
annotation. The TestRule's "apply" function returns a new Statement given the Statement with your test. The new Statement's Execute()
method can call the test Statement's execute method (or not, or call it multiple times), and do whatever it wants before and after
.
Now, JUnit has a new Statement that does more than just run the test, and it can again pass that to any more rules before finally calling Execute.
To get current skin URL use this Mage::getDesign()->getSkinUrl()
JS Code:
<script type="text/javascript">
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML Code:
<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />
Code Behind C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.
$('#textfield').live('keyup', function (event) {
var value=$('#textfield').val();
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var newvalue=value.replace(/,/g, '');
var valuewithcomma=Number(newvalue).toLocaleString('en');
$('#textfield').val(valuewithcomma);
});
<form><input type="text" id="textfield" ></form>
How to remove a tagged image
docker rmi the tag first
docker rmi the image.
# that can be done in one docker rmi call e.g.: # docker rmi <repo:tag> <imageid>
(this works Nov 2016, Docker version 1.12.2)
e.g.
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
usrxx/the-application 16112805 011fd5bf45a2 12 hours ago 5.753 GB
usryy/the-application vx.xx.xx 5af809583b9c 3 days ago 5.743 GB
usrzz/the-application vx.xx.xx eef00ce9b81f 10 days ago 5.747 GB
usrAA/the-application vx.xx.xx 422ba91c71bb 3 weeks ago 5.722 GB
usrBB/the-application v1.00.18 a877aec95006 3 months ago 5.589 GB
$ docker rmi usrxx/the-application:16112805 && docker rmi 011fd5bf45a2
$ docker rmi usryy/the-application:vx.xx.xx && docker rmi 5af809583b9c
$ docker rmi usrzz/the-application:vx.xx.xx eef00ce9b81f
$ docker rmi usrAA/the-application:vx.xx.xx 422ba91c71bb
$ docker rmi usrBB/the-application:v1.00.18 a877aec95006
e.g. Scripted remove anything older than 2 weeks.
IMAGESINFO=$(docker images --no-trunc --format '{{.ID}} {{.Repository}} {{.Tag}} {{.CreatedSince}}' |grep -E " (weeks|months|years)")
TAGS=$(echo "$IMAGESINFO" | awk '{ print $2 ":" $3 }' )
IDS=$(echo "$IMAGESINFO" | awk '{ print $1 }' )
echo remove old images TAGS=$TAGS IDS=$IDS
for t in $TAGS; do docker rmi $t; done
for i in $IDS; do docker rmi $i; done
Just declare it outside class definition.
If your namespace's name is X, you will be able to access the enum's values by X.card_suit
If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i
) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.
The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.
That will almost work.
When pushing to a non-default branch, you need to specify the source ref and the target ref:
git push origin branch1:branch2
Or
git push <remote> <branch with new changes>:<branch you are pushing to>
#!/bin/bash
file=/tmp/foo.bar.gz
echo $file ${file%.*}
outputs:
/tmp/foo.bar.gz /tmp/foo.bar
Note that only the last extension is removed.
So, you can try this solution:
DECLARE @DAY INT = 25
DECLARE @MONTH INT = 10
DECLARE @YEAR INT = 2016
DECLARE @DATE AS DATETIME
SET @DATE = CAST(RTRIM(@YEAR * 10000 + @MONTH * 100 + @DAY) AS DATETIME)
SELECT REPLACE(CONVERT(VARCHAR(10), @DATE, 102), '.', '-') AS EXPECTDATE
Or you can try this a few lines of code:
DECLARE @DAY INT = 25
DECLARE @MONTH INT = 10
DECLARE @YEAR INT = 2016
SELECT CAST(RTRIM(@YEAR * 10000 +'-' + @MONTH * 100+ '-' + @DAY) AS DATE) AS EXPECTDATE
A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)
Great piece of code, thanks for sharing!
I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.
static string GetDataMemberName(string colName, object t) {_x000D_
foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
if (propertyInfo.CanRead) {_x000D_
if (propertyInfo.Name == colName) {_x000D_
var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
return attributes.Name;_x000D_
return colName;_x000D_
}_x000D_
}_x000D_
}_x000D_
return colName;_x000D_
}
_x000D_
Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.
//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====
Class<?> reference = vector.get(0).getClass();
Object obj = reference.newInstance();
Field[] objFields = obj.getClass().getFields();
I was trying to verify the installation of TensorFlow as specified here on a newly created virtual environment on Python 3.6. On running:
pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"
I get the error and/or warning:
tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl is not a supported wheel on this platform.
Since I had previously upgraded from pip to pip3, I simply replaced pip with pip3 as in:
pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"
and it worked like a charm!
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
You should have :
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
This is for Phonegap 3.0.x to 3.3.x. For PhoneGap 3.4.0 and higher see below.
Found part of the answer here, at Phonegap documentation. The full process is the following:
Open a command line window, and go to /path/to/your/project/platforms/android/cordova.
Run build --release
. This creates an unsigned release APK at /path/to/your/project/platforms/android/bin folder, called YourAppName-release-unsigned.apk.
Sign and align the APK using the instructions at android developer official docs.
Thanks to @LaurieClark for the link (http://iphonedevlog.wordpress.com/2013/08/16/using-phonegap-3-0-cli-on-mac-osx-10-to-build-ios-and-android-projects/), and the blogger who post it, because it put me on the track.
This error is a result of the protection level of ClassB
's constructor, not ClassB
itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal
by default. Declaring the constructor public
will fix this problem:
public ClassB() { }
* One could also say that constructors have no name, only a type; this does not change the essence of the problem.
Yes, a foreign key can be a primary key in the case of one to one relationship between those tables
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.
With xunit you have Assert.Throws, so you can do things like this:
[Fact]
public void CantDecrementBasketLineQuantityBelowZero()
{
var o = new Basket();
var p = new Product {Id = 1, NetPrice = 23.45m};
o.AddProduct(p, 1);
Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
}
[Fact] is the xunit equivalent of [TestMethod]
UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL
The standard library includes the ordered and the unordered map (std::map
and std::unordered_map
) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.
An example with (ordered) std::map
:
#include <map>
#include <iostream>
#include <cassert>
int main(int argc, char **argv)
{
std::map<std::string, int> m;
m["hello"] = 23;
// check if key is present
if (m.find("world") != m.end())
std::cout << "map contains key world!\n";
// retrieve
std::cout << m["hello"] << '\n';
std::map<std::string, int>::iterator i = m.find("hello");
assert(i != m.end());
std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
return 0;
}
Output:
23 Key: hello Value: 23
If you need ordering in your container and are fine with the O(log n) runtime then just use std::map
.
Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map
, which has a similar to std::map
API (e.g. in the above example you just have to search and replace map
with unordered_map
).
The unordered_map
container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11
to the CXXFLAGS).
Even before the C++11 release GCC supported unordered_map
- in the namespace std::tr1
. Thus, for old GCC compilers you can try to use it like this:
#include <tr1/unordered_map>
std::tr1::unordered_map<std::string, int> m;
It is also part of boost, i.e. you can use the corresponding boost-header for better portability.
So that works fine, but how on earth do you give the buttons margins so there is space between them?
You call setMargins()
on the LinearLayout.LayoutParams
object.
I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.
LinearLayout.LayoutParams
is a subclass of LinearLayout.MarginLayoutParams
, as indicated in the documentation.
Is this impossible?
No.
it wouldn't be the first Android layout task you can only do in XML
You are welcome to supply proof of this claim.
Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.
You can also do:
document.getElementsByTagName('html')[0].innerHTML
You will not get the Doctype or html tag, but everything else...
They are formatting String
. The Java specific syntax is given in java.util.Formatter
.
The general syntax is as follows:
%[argument_index$][flags][width][.precision]conversion
%02d
performs decimal integer conversion d
, formatted with zero padding (0
flag), with width 2
. Thus, an int
argument whose value is say 7
, will be formatted into "07"
as a String
.
You may also see this formatting string in e.g. String.format
.
These are just some commonly used formats and doesn't cover the syntax exhaustively.
System.out.printf("Agent %03d to the rescue!", 7);
// Agent 007 to the rescue!
You can use the -
flag for left justification; otherwise it'll be right justification.
for (Map.Entry<Object,Object> prop : System.getProperties().entrySet()) {
System.out.printf("%-30s : %50s%n", prop.getKey(), prop.getValue());
}
This prints something like:
java.version : 1.6.0_07
java.vm.name : Java HotSpot(TM) Client VM
java.vm.vendor : Sun Microsystems Inc.
java.vm.specification.name : Java Virtual Machine Specification
java.runtime.name : Java(TM) SE Runtime Environment
java.vendor.url : http://java.sun.com/
For more powerful message formatting, you can use java.text.MessageFormat
. %n
is the newline conversion (see below).
System.out.println(Integer.toHexString(255));
// ff
System.out.printf("%d is %<08X", 255);
// 255 is 000000FF
Note that this also uses the <
relative indexing (see below).
System.out.printf("%+,010.2f%n", 1234.567);
System.out.printf("%+,010.2f%n", -66.6666);
// +01,234.57
// -000066.67
For more powerful floating point formatting, use DecimalFormat
instead.
%n
for platform-specific line separatorSystem.out.printf("%s,%n%s%n", "Hello", "World");
// Hello,
// World
%%
for an actual %
-signSystem.out.printf("It's %s%% guaranteed!", 99.99);
// It's 99.99% guaranteed!
Note that the double
literal 99.99
is autoboxed to Double
, on which a string conversion using toString()
is defined.
n$
for explicit argument indexingSystem.out.printf("%1$s! %1$s %2$s! %1$s %2$s %3$s!",
"Du", "hast", "mich"
);
// Du! Du hast! Du hast mich!
<
for relative indexingSystem.out.format("%s?! %<S?!?!?", "Who's your daddy");
// Who's your daddy?! WHO'S YOUR DADDY?!?!?
MessageFormat
with exampleYou can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
Update your user, domain, and proxy information in cntlm.ini
, then test your proxy with this command (run in your Cntlm installation folder):
cntlm -c cntlm.ini -I -M http://google.ro
It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini
Sample cntlm.ini
:
Username user
Domain domain
# provide actual value if autodetection fails
# Workstation pc-name
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:54321
Listen 192.168.1.42:8080
Gateway no
SOCKS5Proxy 5000
# provide socks auth info if you want it
# SOCKS5User socks-user:socks-password
# printed authentication info from the previous step
Auth NTLMv2
PassNTLMv2 98D6986BCFA9886E41698C1686B58A09
Note: on linux the config file is cntlm.conf
This worked for me...
<asp:RadioButtonList runat="server" ID="Intent">
<asp:ListItem Value="Confirm">Yes!</asp:ListItem>
<asp:ListItem Value="Postpone">Not now</asp:ListItem>
<asp:ListItem Value="Decline">Never!</asp:ListItem>
</asp:RadioButtonList>
The handler:
$(document).ready(function () {
$("#<%=Intent.ClientID%>").change(function(){
var rbvalue = $("input[name='<%=Intent.UniqueID%>']:radio:checked").val();
if(rbvalue == "Confirm"){
alert("Woohoo, Thanks!");
} else if (rbvalue == "Postpone"){
alert("Well, I really hope it's soon");
} else if (rbvalue == "Decline"){
alert("Shucks!");
} else {
alert("How'd you get here? Who sent you?");
}
});
});
The important part: $("input[name='<%=Intent.UniqueID%>']:radio:checked").val();
Make sure your escaping the HTML characters
E.g.
// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
// Escape any html characters
echo htmlentities($_POST['contact_list']);
}
This would occur because of the angle brackets and the browser thinking they are tags.
Yes, you have a }
too many. Anyway, compressing yourself tends to result in errors.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Use Closure Compiler instead.
This is a new answer to an old question about a common misconception about contains()
in XPath...
Summary: contains()
means contains a substring, not contains a node.
This XPath is often misinterpreted:
//ul[contains(li, 'Model')]
Wrong interpretation:
Select those ul
elements that contain an li
element with Model
in it.
This is wrong because
contains(x,y)
expects x
to be a string, andthe XPath rule for converting multiple elements to a string is this:
A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
Right interpretation: Select those ul
elements whose first li
child has a string-value that contains a Model
substring.
XML
<r>
<ul id="one">
<li>Model A</li>
<li>Foo</li>
</ul>
<ul id="two">
<li>Foo</li>
<li>Model A</li>
</ul>
</r>
XPaths
//ul[contains(li, 'Model')]
selects the one
ul
element.
Note: The two
ul
element is not selected because the string-value of the first li
child
of the two
ul
is Foo
, which does not contain the Model
substring.
//ul[li[contains(.,'Model')]]
selects the one
and two
ul
elements.
Note: Both ul
elements are selected because contains()
is applied to each li
individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul
elements do have an li
child whose string value contains the Model
substring -- position of the li
element no longer matters.
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
package com.mani.smsdetect;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
//Declaration Button
Button btnClickMe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intialization Button
btnClickMe = (Button) findViewById(R.id.btnClickMe);
btnClickMe.setOnClickListener(MainActivity.this);
//Here MainActivity.this is a Current Class Reference (context)
}
@Override
public void onClick(View v) {
//Your Logic
}
}
Just in case someone really needs a closure like that, it can be done in the following way:
var categoriesPerPage = [[Int]]()
var numPagesClosure: ()->Int {
return {
return self.categoriesPerPage.count
}
}
I found that I needed 3 interface definitions in order to handle various version of android.
public void openFileChooser(ValueCallback < Uri > uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
FreeHealthTrack.this.startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType) {
openFileChooser(uploadMsg);
}
public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg);
}
Use 'dd-mon-yyyy'
if you are using the 2nd date format specified in your answer. Ex:
to_date(<column name>,'dd-mon-yyyy')
is null
can be used to check whether null
data is coming from a query as in following example:
declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
set @flag= 0;
end
else
begin
set @flag=1;
end
return @flag;
Another common option is when you do want multiple plots in a single window
f = figure;
hold on
plot(x1,y1)
plot(x2,y2)
...
plots multiple data sets on the same (new) figure.
Anybody working with nullable types, Value
is required to use CompareTo
.
objListOrder.Sort((x, y) => x.YourNullableType.Value.CompareTo(y.YourNullableType.Value));
I am quoting this answer from official tensorflow docs https://www.tensorflow.org/api_guides/python/nn#Convolution For the 'SAME' padding, the output height and width are computed as:
out_height = ceil(float(in_height) / float(strides[1]))
out_width = ceil(float(in_width) / float(strides[2]))
and the padding on the top and left are computed as:
pad_along_height = max((out_height - 1) * strides[1] +
filter_height - in_height, 0)
pad_along_width = max((out_width - 1) * strides[2] +
filter_width - in_width, 0)
pad_top = pad_along_height // 2
pad_bottom = pad_along_height - pad_top
pad_left = pad_along_width // 2
pad_right = pad_along_width - pad_left
For the 'VALID' padding, the output height and width are computed as:
out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))
and the padding values are always zero.
Using slicing, e.g. array = array[::-1], is a neat trick and very Pythonic, but a little obscure for newbies maybe. Using the reverse() method is a good way to go in day to day coding because it is easily readable.
However, if you need to reverse a list in place as in an interview question, you will likely not be able to use built in methods like these. The interviewer will be looking at how you approach the problem rather than the depth of Python knowledge, an algorithmic approach is required. The following example, using a classic swap, might be one way to do it:-
def reverse_in_place(lst): # Declare a function
size = len(lst) # Get the length of the sequence
hiindex = size - 1
its = size/2 # Number of iterations required
for i in xrange(0, its): # i is the low index pointer
temp = lst[hiindex] # Perform a classic swap
lst[hiindex] = lst[i]
lst[i] = temp
hiindex -= 1 # Decrement the high index pointer
print "Done!"
# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
print array # Print the original sequence
reverse_in_place(array) # Call the function passing the list
print array # Print reversed list
**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]
Note that this will not work on Tuples or string sequences, because strings and tuples are immutable, i.e., you cannot write into them to change elements.
Have you tried this
Random integer between 0 and 1000(1000 not included):
Random random = new Random();
int randomNumber = random.Next(0, 1000);
Loop it as many times you want
To print the last column of a line just use $(NF):
awk '{print $(NF)}'
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util
version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
You can get all the contact all those which have no number and all those which have no name from this piece of code
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " ASC");
ContactCount = cur.getCount();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
}
if (phone == "" || name == "" || name.equals(phone)) {
if (phone.equals(""))
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
if (name.equals("") || name.equals(phone))
getAllContact.add(new MissingPhoneModelClass(phone, "No Name", id));
} else {
if(TextUtils.equals(phone,null)){
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
}
else {
getAllContact.add(new MissingPhoneModelClass(phone, name, id));
}
}
}
}
}
One thing can be done you have to give the permission in the manifest for contact READ and WRITE After that you can create the model class for the list which can be use to add all the contact here is the model class
public class PhoneModelClass {
private String number;
private String name;
private String id;
private String rawId;
public PhoneModelClass(String number, String name, String id, String rawId) {
this.number = number;
this.name = name;
this.id = id;
this.rawId = rawId;
}
public PhoneModelClass(String number, String name, String id) {
this.number = number;
this.name = name;
this.id = id;
}
public String getRawId() {
return rawId;
}
public void setRawId(String rawId) {
this.rawId = rawId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Enjoy :)
Figured it out
class AnimatedFlutterLogo extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}
class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
Timer _timer;
FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;
_AnimatedFlutterLogoState() {
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
_logoStyle = FlutterLogoStyle.horizontal;
});
});
}
@override
void dispose() {
super.dispose();
_timer.cancel();
}
@override
Widget build(BuildContext context) {
return new FlutterLogo(
size: 200.0,
textColor: Palette.white,
style: _logoStyle,
);
}
}
UPDATE: Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:
@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })
you simply can do this:
@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })
Benefits: You haven't to call .TextBoxFor
, etc. for templates. Just call .EditorFor
.
While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-template
that can handles readonly
attribute:
EditorTemplates
in ~/Views/Shared/
PartialView
named String.cshtml
Fill the String.cshtml
with this code:
@if(ViewData.ModelMetadata.IsReadOnly) {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
} else {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line" })
}
In model class, put the [ReadOnly(true)]
attribute on properties which you want to be readonly
.
For example,
public class Model {
// [your-annotations-here]
public string EditablePropertyExample { get; set; }
// [your-annotations-here]
[ReadOnly(true)]
public string ReadOnlyPropertyExample { get; set; }
}
Now you can use Razor's default syntax simply:
@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)
The first one renders a normal text-box
like this:
<input class="text-box single-line" id="field-id" name="field-name" />
And the second will render to;
<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />
You can use this solution for any type of data (DateTime
, DateTimeOffset
, DataType.Text
, DataType.MultilineText
and so on). Just create an editor-template
.
You should have access to the POST dictionary on the request object.
I ended up with this script:
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%
set year=%date:~-4%
echo year=%year%
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%
set datetimef=%year%%month%%day%_%hour%%min%%secs%
echo datetimef=%datetimef%
In nutshell: CANDIDATE KEY is a minimal SUPER KEY.
Where Super key is the combination of columns(or attributes) that uniquely identify any record(or tuple) in a relation(table) in RDBMS.
For instance, consider the following dependencies in a table having columns A, B, C, and D (Giving this table just for a quick example so not covering all dependencies that R could have).
Attribute set (Determinant)---Can Identify--->(Dependent)
A-----> AD
B-----> ABCD
C-----> CD
AC----->ACD
AB----->ABCD
ABC----->ABCD
BCD----->ABCD
Now, B, AB, ABC, BCD identifies all columns so those four qualify for the super key.
But, B?AB; B?ABC; B?BCD hence AB, ABC, and BCD disqualified for CANDIDATE KEY as their subsets could identify the relation, so they aren't minimal and hence only B is the candidate key, not the others.
One more thing Primary key is any one among the candidate keys.
Thanks for asking
Just add the FormsModule
in the imports
array of app.module.ts
file,
and add import { FormsModule } from '@angular/forms';
at the top of this file...this will work.
import csv
with open(filename) as f:
csvreader = csv.reader(f)
for line in csvreader:
print(line[0])
Based on my findings...
This Javascript error occurs when you execute button() on an element with a selector and try to use a function/method of button() with a different selector on the same element.
For example, here is the HTML:
<input type="submit" name="continue" id="mybuttonid" class="mybuttonclass" value="Continue" />
So you execute button() on it:
jQuery(document).ready(function() { jQuery('.mybuttonclass').button(); });
Then you try to disable it, this time not using the class as you initiated it but rather using the ID, then you'll get the error as this thread is titled:
jQuery(document).ready(function() { jQuery('#mybuttonid').button('option', 'disabled', true); });
So rather use the class again as you initiated it, that'll resolve the problem.
I needed to detect IE vs most everything else and I didn't want to depend on the UA string. I found that using es6number
with Modernizr did exactly what I wanted. I don't have much concern with this changing as I don't expect IE to ever support ES6 Number. So now I know the difference between any version of IE vs Edge/Chrome/Firefox/Opera/Safari.
More details here: http://caniuse.com/#feat=es6-number
Note that I'm not really concerned about Opera Mini false negatives. You might be.
A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:
<label for="child-input-1">
<input type="radio" id="child-input-1"/>
<span> Associate the following text with the selected radio button: </span>
<input type="text" id="child-input-2"/>
</label>
While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.
Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.
`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
FOR EACH ROW
BEGIN
**SET @tableId= (SELECT id FROM dummy LIMIT 1);**
END;`;
See this article on alistapart.com. (Ed: The article has been updated since originally linked)
self
is being used to maintain a reference to the original this
even as the context is changing. It's a technique often used in event handlers (especially in closures).
Edit: Note that using self
is now discouraged as window.self
exists and has the potential to cause errors if you are not careful.
What you call the variable doesn't particularly matter. var that = this;
is fine, but there's nothing magic about the name.
Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.
For example, a simple event callback:
function MyConstructor(options) {_x000D_
let that = this;_x000D_
_x000D_
this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
document.addEventListener('click', (event) => {_x000D_
alert(that.someprop);_x000D_
});_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
someprop: "Hello World"_x000D_
});
_x000D_
Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.
My answer comes from here
You can make a derived class, which will set the timeout property of the base WebRequest
class:
using System;
using System.Net;
public class WebDownload : WebClient
{
/// <summary>
/// Time in milliseconds
/// </summary>
public int Timeout { get; set; }
public WebDownload() : this(60000) { }
public WebDownload(int timeout)
{
this.Timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = this.Timeout;
}
return request;
}
}
and you can use it just like the base WebClient class.
Another way to do this is:
mongo mongodb://mongoDbIPorDomain:port
You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.
You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.
Another one is:
{{ myentity.text[:50] ~ '...' }}
Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused
.
There is no property for video element for getting the playing status. But there is one event "playing" which will be triggered when it starts to play. Event "ended" is triggered when it stops playing.
So the solution is
This page will give you a better idea about video events. Play the video on this page and see how events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html
The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
Well, if there's anyone out there on a shared hosting and with no access to php.ini
file, you can set this line of code at the very top of your PHP files:
ini_set('always_populate_raw_post_data', -1);
Works more of the same. I hope it saves someone some debugging time :)
I'm aware that there are several answers here, but this is what I came up with. This only handles MySQL DATETIME values as per the original question I was responding to. The array $a needs some work. I welcome comments on how to improve. Call as:
echo time_elapsed_string('2014-11-14 09:42:28');
function time_elapsed_string($ptime)
{
// Past time as MySQL DATETIME value
$ptime = strtotime($ptime);
// Current time as MySQL DATETIME value
$csqltime = date('Y-m-d H:i:s');
// Current time as Unix timestamp
$ctime = strtotime($csqltime);
// Elapsed time
$etime = $ctime - $ptime;
// If no elapsed time, return 0
if ($etime < 1){
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str){
// Divide elapsed time by seconds
$d = $etime / $secs;
if ($d >= 1){
// Round to the next lowest integer
$r = floor($d);
// Calculate time to remove from elapsed time
$rtime = $r * $secs;
// Recalculate and store elapsed time for next loop
if(($etime - $rtime) < 0){
$etime -= ($r - 1) * $secs;
}
else{
$etime -= $rtime;
}
// Create string to return
$estring = $estring . $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ';
}
}
return $estring . ' ago';
}
You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)
From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.
Silverlight doesn't support the MidpointRounding option. Here's an extension method for Silverlight that adds the MidpointRounding enum:
public enum MidpointRounding
{
ToEven,
AwayFromZero
}
public static class DecimalExtensions
{
public static decimal Round(this decimal d, MidpointRounding mode)
{
return d.Round(0, mode);
}
/// <summary>
/// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding
/// </summary>
/// <param name="d">A Decimal number to be rounded.</param>
/// <param name="decimals">The number of significant fractional digits (precision) in the return value.</param>
/// <returns>The number nearest d with precision equal to decimals. If d is halfway between two numbers, then the nearest whole number away from zero is returned.</returns>
public static decimal Round(this decimal d, int decimals, MidpointRounding mode)
{
if ( mode == MidpointRounding.ToEven )
{
return decimal.Round(d, decimals);
}
else
{
decimal factor = Convert.ToDecimal(Math.Pow(10, decimals));
int sign = Math.Sign(d);
return Decimal.Truncate(d * factor + 0.5m * sign) / factor;
}
}
}
Source: http://anderly.com/2009/08/08/silverlight-midpoint-rounding-solution/
Update 2019
Bootstrap 4 - The Navbar is transparent by default
Most of the answers here are misleading because they relate to Bootstrap 3. By default, the Bootstrap 4 Navbar is transparent. Just remember to use navbar-light
or navbar-dark
so the link colors work against the contrast of the background color...
https://www.codeply.com/go/FTDyj4KZlQ
<nav class="navbar navbar-expand-sm fixed-top navbar-light">
<div class="container">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar1">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</div>
</nav>
The compiler wants to know the function before it can use it
just declare the function before you call it
#include <stdio.h>
int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now
int main(int argc, const char * argv[])
{
int input;
printf("Please give me a number : ");
scanf("%d", &input);
getchar();
printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!
}/* main */
int Fibonacci(int number)
{
//…
Fedora/Cent Os same trouble when used yum install and interrupt it with Ctrl+Z.
Use this command:
sudo cat /var/cache/dnf/*pid
if there any pid, you can manually remove it:
sudo nano /var/cache/dnf/*pid
crtl+x followed by Y and Enter to exit nano editor (you can use any editor you want to open).
If after, delete some tmp files that may still be there:
sudo systemd-tmpfiles --remove dnf.conf
You have added the add marker method call outside the function and that causes it to execute before the initialize method which will be called when google maps script loads and thus the marker is not added because map is not initialized Do as below.... Create separate method TestMarker and call it from initialize.
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
</script>
What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.
You can always count the collection. For example $mentor->intern->count()
will return how many intern does a mentor have.
https://laravel.com/docs/5.2/collections#method-count
In your code you can do something like this
foreach($mentors as $mentor)
@if($mentor->intern->count() > 0)
@foreach($mentor->intern as $intern)
<tr class="table-row-link" data-href="/werknemer/{!! $intern->employee->EmployeeId !!}">
<td>{{ $intern->employee->FirstName }}</td>
<td>{{ $intern->employee->LastName }}</td>
</tr>
@endforeach
@else
Mentor don't have any intern
@endif
@endforeach
What I do when it happens is Disable the COM port into the Device Manager and Enable it again.
It stop the communications with another program or thread and become free for you.
I hope this works for you. Regards.
I had this issue until I removed the project in question from the server's deployments (in JBoss Dev Studio, right-click the server and "Remove" the project in the Servers view), then did the following:
After this, just restart the server (in debug or run mode) by selecting the server, NOT the project itself.
This seemed to flush any previous settings/states/memory/whatever that was causing the issue, and I no longer got the error.