ContextLoaderListener
has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml
You can customize this by using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>
on web.xml
, or remove this listener if you don't need one.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
What is it?
WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.
This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.
One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.
An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.
The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.
What is it not?
WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.
As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.
When should I not use it?
Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.
select add_months(trunc(sysdate,'MM'),1) - trunc(sysdate,'MM') from dual;
Some sites are detecting this:
function d() {
try {
if (window.document.$cdc_asdjflasutopfhvcZLmcfl_.cache_)
return !0
} catch (e) {}
try {
//if (window.document.documentElement.getAttribute(decodeURIComponent("%77%65%62%64%72%69%76%65%72")))
if (window.document.documentElement.getAttribute("webdriver"))
return !0
} catch (e) {}
try {
//if (decodeURIComponent("%5F%53%65%6C%65%6E%69%75%6D%5F%49%44%45%5F%52%65%63%6F%72%64%65%72") in window)
if ("_Selenium_IDE_Recorder" in window)
return !0
} catch (e) {}
try {
//if (decodeURIComponent("%5F%5F%77%65%62%64%72%69%76%65%72%5F%73%63%72%69%70%74%5F%66%6E") in document)
if ("__webdriver_script_fn" in document)
return !0
} catch (e) {}
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
If anyone use WPF Modern UI,they cant use OnTabSelected event.but they can use SelectedSourceChanged event.
like this
<mui:ModernTab Layout="Tab" SelectedSourceChanged="ModernTab_SelectedSourceChanged" Background="Blue" AllowDrop="True" Name="tabcontroller" >
C# code is
private void ModernTab_SelectedSourceChanged(object sender, SourceEventArgs e)
{
var links = ((ModernTab)sender).Links;
var link = this.tabcontroller.Links.FirstOrDefault(l => l.Source == e.Source);
if (link != null) {
var index = this.tabcontroller.Links.IndexOf(link);
MessageBox.Show(index.ToString());
}
}
$('#myDiv').hide();
hide function is used to edit content and show function is used to show again.
For more please click on this link.
just copy your source DataBase(from your PC C:\xampp\mysql\data\"your data base"), then copy it to the destination folder in your MAC (/Application/Xampp/xamppfiles/var/mysql).
don't forget to set the permission of the new copied folder(your DataBase) in your MAC otherwise you can't see your tables!
to set the permission: -go to the folder of your DataBase(/Application/Xampp/xamppfiles/var/mysql/"your data base") -right click on it -select Get info -in the sharing&permissions you must add your user account(i.e. administrator or everyone) -choose its privilege to Read & Write -choose Apply to enclosed items
enjoy your Database ;)
I had no idea what file was having the lock so what I did to get out of this issue was:
This worked for me.
add java security in your run command
java -jar -Djava.security.egd="file:///dev/urandom" yourjarfilename.jar
@echo off
set startbuild=%TIME%
C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error
copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q
echo Start Copy: %TIME%
set copystart=%TIME%
xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d
del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm
echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%
c:\link\warnings.log
:error
c:\link\errors.log
CSS
body { margin: 0; }
canvas { display: block; }
JavaScript
window.addEventListener("load", function()
{
var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height);
context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height);
context.stroke();
}
function resize()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
window.addEventListener("resize", resize);
resize();
});
"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.
But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.
public class StringCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "siddhartha";
String s2 = "";
String s3 = null;
System.out.println("length s1 ="+s1.length());
System.out.println("length s2 ="+s2.length());
//this piece of code will still throw nullpointerexception .
if(s3 != ""){
System.out.println("length s3 ="+s3.length());
}
}
}
in array example,Its same in php (in_array)
var ur_fit = ["slim_fit", "tailored", "comfort"];
var ur_length = ["length_short", "length_regular", "length_high"];
if(ur_fit.indexOf(data_this)!=-1){
alert("Value is avail in ur_fit array");
}
else if(ur_length.indexOf(data_this)!=-1){
alert("value is avail in ur_legth array");
}
ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.
Here's the relevent section of the spec:
Element Declaration Schema Component Property {target namespace} Representation If form is present and its ·actual value· is qualified, or if form is absent and the ·actual value· of elementFormDefault on the <schema> ancestor is qualified, then the ·actual value· of the targetNamespace [attribute] of the parent <schema> element information item, or ·absent· if there is none, otherwise ·absent·.
What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".
For example: If elementFormDefault is unqualified -
<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>
will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.
To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.
You have to queue the rest of your request for it to work.
var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;
elems.each( function(i) {
$(this).fadeOut(200, function() {
$(this).remove();
if (i == lastID) {
$j(this).queue("fx",function(){ doMyThing;});
}
});
});
I also had the same issue. Tried all ways and it didn't work out until I added the following in app.module.ts
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
And add the following in your imports in app.module.ts
Ng4LoadingSpinnerModule.forRoot()
This case might be rare but I hope this helps someone out there
Meridian pertains to AM/PM, by setting it to false you're indicating you don't want AM/PM, therefore you want 24-hour clock implicitly.
$('#timepicker1').timepicker({showMeridian:false});
I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
If you need step-by-step you can read this great article:
Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)
import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1
u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0
#option 1
#keep index of t
u.index = t.index
#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)
#now concat will keep number of rows
r=pd.concat([t,u], axis=1)
There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs
, cache
, uploads
directories etc.
So what I always do is to add a .gitignore
file in those directories with the following content:
*
!.gitignore
With this .gitignore
file, Git will not track any files in those directories yet still allow me to add the .gitignore
file and hence the directory itself to the repo.
SuppressFinalize
should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this
object was cleaned up fully.
The recommended IDisposable
pattern when you have a finalizer is:
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// called via myClass.Dispose().
// OK to use any private object references
}
// Release unmanaged resources.
// Set large fields to null.
disposed = true;
}
}
public void Dispose() // Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
Dispose(false);
}
}
Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize
tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.
The SuppressFinalize
optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize
on other objects mind you. That's a serious defect waiting to happen.
Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable
, but if you have a finalizer you should implement IDisposable
to allow deterministic cleanup of your class.
Most of the time you should be able to get away with IDisposable
to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.
Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable
classes in order to test that code has disposed their IDisposable
object properly.
public void Dispose() // Implement IDisposable
{
Dispose(true);
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#if DEBUG
~MyClass() // the finalizer
{
Dispose(false);
}
#endif
I have a little extension to the solutions.
Using a recursive generic declaration and a deriving subclass you can better concentrate on your actual target.
Notice, it's different from a non generic implementation, you don`t need to cast 'node' in 'NodeWorker'.
Here's my example:
public class GenericTree<T> where T : GenericTree<T> // recursive constraint
{
// no specific data declaration
protected List<T> children;
public GenericTree()
{
this.children = new List<T>();
}
public virtual void AddChild(T newChild)
{
this.children.Add(newChild);
}
public void Traverse(Action<int, T> visitor)
{
this.traverse(0, visitor);
}
protected virtual void traverse(int depth, Action<int, T> visitor)
{
visitor(depth, (T)this);
foreach (T child in this.children)
child.traverse(depth + 1, visitor);
}
}
public class GenericTreeNext : GenericTree<GenericTreeNext> // concrete derivation
{
public string Name {get; set;} // user-data example
public GenericTreeNext(string name)
{
this.Name = name;
}
}
static void Main(string[] args)
{
GenericTreeNext tree = new GenericTreeNext("Main-Harry");
tree.AddChild(new GenericTreeNext("Main-Sub-Willy"));
GenericTreeNext inter = new GenericTreeNext("Main-Inter-Willy");
inter.AddChild(new GenericTreeNext("Inter-Sub-Tom"));
inter.AddChild(new GenericTreeNext("Inter-Sub-Magda"));
tree.AddChild(inter);
tree.AddChild(new GenericTreeNext("Main-Sub-Chantal"));
tree.Traverse(NodeWorker);
}
static void NodeWorker(int depth, GenericTreeNext node)
{ // a little one-line string-concatenation (n-times)
Console.WriteLine("{0}{1}: {2}", String.Join(" ", new string[depth + 1]), depth, node.Name);
}
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$ Bookmark line
Regular expression
(under Search Mode
)Mark All
(this will find the regex and highlights all the lines and bookmark them) Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
Check this sample out from the Highcharts API.
Replace this
return Highcharts.dateFormat('%a %d %b', this.value);
With this
return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);
Look here about the dateFormat()
function.
Also see - tickInterval and pointInterval
The short answer is that --ignore-times
does more than its name implies. It ignores both the time and size.
In contrast, --size-only
does exactly what it says.
The long answer is that rsync
has three ways to decide if a file is outdated:
These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.
By default, rsync
uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat
, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:
By using --size-only
, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.
By using --ignore-times
, neither of 1, 2 or 3 is performed. A file is always copied.
By using --checksum
, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.
num.toStringAsFixed()
rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:
n = num.parse(n.toStringAsFixed(2));
The most common ways to use the shutdown
command are:
shutdown -s
— Shuts down.shutdown -r
— Restarts.shutdown -l
— Logs off.shutdown -h
— Hibernates.
Note: There is a common pitfall wherein users think -h
means "help" (which it does for every other command-line program... except shutdown.exe
, where it means "hibernate"). They then run shutdown -h
and accidentally turn off their computers. Watch out for that.
shutdown -i
— "Interactive mode". Instead of performing an action, it displays a GUI dialog.
shutdown -a
— Aborts a previous shutdown command.The commands above can be combined with these additional options:
-f
— Forces programs to exit. Prevents the shutdown process from getting stuck.-t <seconds>
— Sets the time until shutdown. Use -t 0
to shutdown immediately.-c <message>
— Adds a shutdown message. The message will end up in the Event Log.-y
— Forces a "yes" answer to all shutdown queries.
Note: This option is not documented in any official documentation. It was discovered by these StackOverflow users.
I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.
-f
option from JosephStyonsrundll32
from VonCI once had to write such a regex for a company I worked for. The solution was this:
Example regex:
.*([^\.]+)(com|net|org|info|coop|int|co\.uk|org\.uk|ac\.uk|uk|__and so on__)$
This worked really well and also matched weird, unofficial top-levels like de.com and friends.
The upside:
The downside of this solution is of course:
You copy and paste the following code. It will display all the tables with Name and Created Date
SELECT object_name,created FROM user_objects
WHERE object_name LIKE '%table_name%'
AND object_type = 'TABLE';
Note: Replace '%table_name%' with the table name you are looking for.
Functions cannot be used to modify base table information, use a stored procedure.
used the following snippet and it worked fine..
.smallText .bmv-disclaimer {
height: 40px;
}
I have removed it from my references.Then run this in Package Manager Console
Install-Package WebMatrix.Data
Finally add WebMatrix.WebData assembly to references,and rebuild project.It works for me.I hope it solves your problem too.
Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length]
+ 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:
I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).
As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.
Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!
C does not have its own String data type like Java.
Only we can declare String datatype in C using character array or character pointer For example :
char message[10];
or
char *message;
But you need to declare at least:
char message[14];
to copy "Hello, world!" into message variable.
As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.
I recommend using subprocess
if writing a beautiful and readable code is your cup of tea:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
And if you are not a software engineer, then maybe consider using Jupyter; you can simply type bash commands:
!rm -r my_dir
Traditionally, you use shutil
:
import shutil
shutil.rmtree(my_dir)
db.collection_name.find({"filed_name":{$exists:true}});
fetch documents that contain this filed_name even it is null.
Warning
db.collection_name.find({"filed_name":{$ne:null}});
fetch documents that its field_name has a value $ne to null but this value could be an empty string also.
My proposition:
db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})
I didn't like any of these answers so I made my own. I don't know if this is ANSI C or not, it's just GCC 4.2.1 in it's default mode. I never can remember the bracketing so I start with a subset of my data and do battle with compiler error messages until it shuts up. Readability is my first priority.
// in a header:
typedef unsigned char uchar;
struct fields {
uchar num;
uchar lbl[35];
};
// in an actual c file (I have 2 in this case)
struct fields labels[] = {
{0,"Package"},
{1,"Version"},
{2,"Apport"},
{3,"Architecture"},
{4,"Bugs"},
{5,"Description-md5"},
{6,"Essential"},
{7,"Filename"},
{8,"Ghc-Package"},
{9,"Gstreamer-Version"},
{10,"Homepage"},
{11,"Installed-Size"},
{12,"MD5sum"},
{13,"Maintainer"},
{14,"Modaliases"},
{15,"Multi-Arch"},
{16,"Npp-Description"},
{17,"Npp-File"},
{18,"Npp-Name"},
{19,"Origin"}
};
The data may start life as a tab-delimited file that you search-replace to massage into something else. Yes, this is Debian stuff. So one outside pair of {} (indicating the array), then another pair for each struct inside. With commas between. Putting things in a header isn't strictly necessary, but I've got about 50 items in my struct so I want them in a separate file, both to keep the mess out of my code and so it's easier to replace.
Not sure if you have resolved it (and if I understand correctly), but here's my idea:
If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).
Try this:
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'parent': {
props: ['myProp'],
computed: {
myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
}
},
'child': {
props: ['myProp'],
watch: {
myProp(val, oldval) { now val will differ from oldval }
}
}
}
}
and in html:
<child :my-prop="myInnerProp"></child>
actually you have to be very careful when working on complex collections in such situations (passing down few times)
Yes, you can add a UNIQUE constraint after the fact. However, if you have non-unique entries in your table Postgres will complain about it until you correct them.
What about this ?
create table dbo.[Address]
(
Id int identity not null,
City nvarchar(255) not null,
Street nvarchar(255) not null,
CONSTRAINT PK_Address PRIMARY KEY (Id)
)
create table dbo.[Person]
(
Id int identity not null,
AddressId int not null,
FirstName nvarchar(255) not null,
LastName nvarchar(255) not null,
CONSTRAINT PK_Person PRIMARY KEY (Id),
CONSTRAINT FK_Person_Address FOREIGN KEY (AddressId) REFERENCES dbo.[Address] (Id)
)
SELECT MAX(id) FROM TABELNAME
This identifies the largest id and returns the value
add this ddl to reference to your project: System.Web.Extensions.dll
use this namespace: using System.Web.Script.Serialization;
public class IdName
{
public int Id { get; set; }
public string Name { get; set; }
}
string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
position: fixed;
will also "pop" an element out of the flow, as you say. :)
position: absolute
must be accompanied by a position. e.g. top: 1rem; left: 1rem
position: fixed
however, will place the element where it would normally appear according to the document flow, but prevent it from moving after that. It also effectively set's the height to 0px (with regards to the dom) so that the next element shifts up over it.
This can be pretty cool, because you can set position: fixed; z-index: 1
(or whatever z-index you need) so that it "pops" over the next element.
This is especially useful for fixed position headers that stay at the top when you scroll, for example.
Run this from the branch where you want the file to end up:
git checkout otherbranch myfile.txt
General formulas:
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
Some notes (from comments):
myfile.txt
and mydir
an alternative:
git show commit_id:path/to/file > path/to/file
While the proposed solutions work, I was trying to implement with Full Calendar and it would require over 90 database calls for each view (as it loads current, previous, and next month), which, I wasn't too thrilled about.
I found an recursion library https://github.com/tplaner/When where you simply store the rules in the database and one query to pull all the relevant rules.
Hopefully this will help someone else, as I spent so many hours trying to find a good solution.
Edit: This Library is for PHP
Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.
From the docs all known implementing classes:
You can use any of above based on your requirement to initiate a Queue object.
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.
SELECT * FROM datapump_dir_objs;
The view shows the NAME
of the directory object, the PATH
as well as READ
and WRITE
permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.
<div class="headerdivider"></div>
and
.headerdivider {
border-left: 1px solid #38546d;
background: #16222c;
width: 1px;
height: 80px;
position: absolute;
right: 250px;
top: 10px;
}
You haven't specified what kind of html element you are trying to do an absolute xpath search on. In your case, it's the input element.
Try this:
element = findElement(By.xpath("//input[@class='t-TextBox' and @type='email' and @test-
id='test-username']");
It will add an extra in your options but your problem will be solved.
<?php
if ($editing == Yes) {
echo "<option value=\".$MyValue.\" SELECTED>".$MyValue."</option>";
}
?>
You can also have this
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)
I would first concatenate the arrays, then I would return only the unique value.
You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array
.
In your case with arrays array1
and array2
it would look like this:
array1.concat(array2)
- concatenate the two arraysarray1.concat(array2).unique()
- return only the unique values. Here unique()
is a method you added to the prototype for Array
.The whole thing would look like this:
Array.prototype.unique = function () {_x000D_
var r = new Array();_x000D_
o: for(var i = 0, n = this.length; i < n; i++)_x000D_
{_x000D_
for(var x = 0, y = r.length; x < y; x++)_x000D_
{_x000D_
if(r[x]==this[i])_x000D_
{_x000D_
continue o;_x000D_
}_x000D_
}_x000D_
r[r.length] = this[i];_x000D_
}_x000D_
return r;_x000D_
}_x000D_
var array1 = [34,35,45,48,49];_x000D_
var array2 = [34,35,45,48,49,55];_x000D_
_x000D_
// concatenate the arrays then return only the unique values_x000D_
console.log(array1.concat(array2).unique());
_x000D_
Step 1
If you have a small file Read all the file data in to memory
Step 2
Convert file data string into Array
Step 3
Search the array to find a location where you want to insert the text
Step 4
Once you have the location insert your text
yourArray.splice(index,0,"new added test");
Step 5
convert your array to string
yourArray.join("");
Step 6
write your file like so
fs.createWriteStream(yourArray);
This is not advised if your file is too big
ToggleButton
inherits from TextView
so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@android:drawable/ic_menu_info_details"
android:gravity="center"
android:textOff=""
android:textOn=""
android:textSize="0dp" />
The result compared to regular ToggleButton
looks like
The seconds option is to use an ImageSpan
to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.
You create a plain ToggleButton
<ToggleButton
android:id="@+id/toggleButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false" />
Then set the "text" programmatially
ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);
The result here in the middle - icon is placed slightly lower since it takes the place of the text.
Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" +$myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).
I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:
borrowed from: https://gist.github.com/gsakkis/4572159
The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:
# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime
from sqlalchemy.orm import Query
try:
basestring
except NameError:
basestring = str
def render_query(statement, dialect=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if dialect is None:
dialect = statement.session.bind.dialect
statement = statement.statement
elif dialect is None:
dialect = statement.bind.dialect
class LiteralCompiler(dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_array_value(self, val, item_type):
if isinstance(val, list):
return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
return self.render_literal_value(val, item_type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (basestring, date, datetime, timedelta)):
return "'%s'" % str(value).replace("'", "''")
elif isinstance(value, list):
return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(dialect, statement).process(statement)
Tested to two levels of nested arrays.
Yes! You can Debug Android Application While you are developing them follow these steps.. Make sure that you have PC suite of the mobile manufacturer. For Example:if you are using samsung you should have samsung kies
1.Enable USB debugging on your device:Settings > Applications > Development > USB debugging
2.Enable Unknownresources:Settings>Unknowresoures
3.Connect your device to PC
4.Select your Application Right click it: RunAS>Run configurations>Choose Device>Target Select your device Run.
You can also without using debugging cable.For that you need to install Airdroid in your device.After installing enter the link in your browser and Drag and Drop .apk file.
Happy Coding!
The problem with UTF-8 is that it is not the most space efficient encoding. Also, some random binary byte sequences are invalid UTF-8 encoding. So you can't just interpret a random binary byte sequence as some UTF-8 data because it will be invalid UTF-8 encoding. The benefit of this constrain on the UTF-8 encoding is that it makes it robust and possible to locate multi byte chars start and end whatever byte we start looking at.
As a consequence, if encoding a byte value in the range [0..127] would need only one byte in UTF-8 encoding, encoding a byte value in the range [128..255] would require 2 bytes ! Worse than that. In JSON, control chars, " and \ are not allowed to appear in a string. So the binary data would require some transformation to be properly encoded.
Let see. If we assume uniformly distributed random byte values in our binary data then, on average, half of the bytes would be encoded in one bytes and the other half in two bytes. The UTF-8 encoded binary data would have 150% of the initial size.
Base64 encoding grows only to 133% of the initial size. So Base64 encoding is more efficient.
What about using another Base encoding ? In UTF-8, encoding the 128 ASCII values is the most space efficient. In 8 bits you can store 7 bits. So if we cut the binary data in 7 bit chunks to store them in each byte of an UTF-8 encoded string, the encoded data would grow only to 114% of the initial size. Better than Base64. Unfortunately we can't use this easy trick because JSON doesn't allow some ASCII chars. The 33 control characters of ASCII ( [0..31] and 127) and the " and \ must be excluded. This leaves us only 128-35 = 93 chars.
So in theory we could define a Base93 encoding which would grow the encoded size to 8/log2(93) = 8*log10(2)/log10(93) = 122%. But a Base93 encoding would not be as convenient as a Base64 encoding. Base64 requires to cut the input byte sequence in 6bit chunks for which simple bitwise operation works well. Beside 133% is not much more than 122%.
This is why I came independently to the common conclusion that Base64 is indeed the best choice to encode binary data in JSON. My answer presents a justification for it. I agree it isn't very attractive from the performance point of view, but consider also the benefit of using JSON with it's human readable string representation easy to manipulate in all programming languages.
If performance is critical than a pure binary encoding should be considered as replacement of JSON. But with JSON my conclusion is that Base64 is the best.
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I know it's an old question but I want to help. You can put the transactional annotation on the service method you need, in this case findTopicByID(id) should have
@Transactional(propagation=Propagation.REQUIRED, readOnly=true, noRollbackFor=Exception.class)
more info about this annotation can be found here
About the other solutions:
fetch = FetchType.EAGER
is not a good practice, it should be used ONLY if necessary.
Hibernate.initialize(topics.getComments());
The hibernate initializer binds your classes to the hibernate technology. If you are aiming to be flexible is not a good way to go.
Hope it helps
I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.
In Powershell 5.1, you want to use continue
to move onto the next item in your loop. I tested with 6 items in an array, had a foreach
loop through, but put an if statement with:
foreach($i in $array){
write-host -fore green "hello $i"
if($i -like "something"){
write-host -fore red "$i is bad"
continue
write-host -fore red "should not see this"
}
}
Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i
matched, I saw something is bad
and then it went on to the next item in the array without saying should not see this
. I tested with return
and it exited the loop altogether.
The default fonts are different across Windows, Mac, and Linux. As of VSCode 1.15.1, the default font settings can be found in the source code:
const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
const DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'Courier New\', monospace, \'Droid Sans Fallback\'';
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
Here is a simple way i did it in my project.
lets say you need to use clipboard.min.js
and for the sake of the example lets say that inside clipboard.min.js
there is a function that called test2()
.
in order to use test2() function you need:
clipboard.min.js
to your component.here are only the relevant parts from my project (see the comments):
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/src/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function (err) { console.error(err); });
</script>
<!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
<script src="app/txtzone/clipboard.min.js"></script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
app.component.ts:
import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js
@Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
export class TxtZoneComponent implements AfterViewInit {
// call test2
callTest2()
{
new test2(); // the javascript function will execute
}
}
I was looking for the same information. Finally found the answer from the link on the answer above by @Straseus
http://arguments.callee.info/2010/04/20/running-apache-and-node-js-together/
Here is the final solution to run apache website on port 80, node js service on port 8080 and use .htaccess RewriteRule
In the DocumentRoot of the apache website, add the following:
Options +FollowSymLinks -MultiViews
<IfModule mod_rewrite.c>
RewriteEngine on
# Simple URL redirect:
RewriteRule ^test.html$ http://arguments.callee.info:8000/test/ [P]
# More complicated (the user sees only "benchmark.html" in their address bar)
RewriteRule ^benchmark.html$ http://arguments.callee.info:8000/node?action=benchmark [P]
# Redirect a whole subdirectory:
RewriteRule ^node/(.*) http://arguments.callee.info:8000/$1 [P]
For the directory level redirect, the link above suggested (.+) rule, which requires one or more character after the 'node/'. I had to convert it to (.*) which is zero or more for my stuff to work.
Thanks a lot for the link @Straseus
that's not true. /mnt/sdcard/external_sd can exist even if the SD card is not mounted. your application will crash when you try to write to /mnt/sdcard/external_sd when it's not mounted.
you need to check if the SD card is mounted first using:
boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
Another more recent and object style way to do it :
$date = new DateTime('now');
$date->add(new DateInterval('P7D'));
Here are a few ways to do it
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
from SOMETABLEWITHTONSOFROWS LIMIT 3;
or
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
or
INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip)
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
Just use padding top and bottom, it will automatically center the content vertically.
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.
<div id="main" class="container" role="main">
<div class="row">
<div class="span5 offset1">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
<div class="span6">
Image Here (TODO)
</div>
</div>
Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.
I think I know what you are doing wrong. If you are applying padding to the span6
like this:
<div class="span6" style="padding-left:5px;">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
It is wrong. What you have to do is add padding to the elements inside:
<div class="span6">
<h2 style="padding-left:5px;">Welcome</h2>
<p style="padding-left:5px;">Hello and welcome to my website.</p>
</div>
I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?
Here's what I did:
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
And annotated each Date field's setter method with this:
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
The "pause" command was a function button underneath my right shift key, so the below combination of keys did the trick for me.
Ctrl + Fn + Shift
Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs
Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.
// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.
use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
let mut map = HashMap::new();
map.insert("James", vec!["user", "admin"]);
map.insert("Jim", vec!["user"]);
map
};
}
fn show_access(name: &str) {
let access = PRIVILEGES.get(name);
println!("{}: {:?}", name, access);
}
fn main() {
let access = PRIVILEGES.get("James");
println!("James: {:?}", access);
show_access("Jim");
}
PROBLEM You're using SQLite3, your DATABASE_NAME is set to the database file's full path, the database file is writeable by Apache, but you still get the above error.
SOLUTION Make sure Apache can also write to the parent directory of the database. SQLite needs to be able to write to this directory.
Make sure each folder of your database file's full path does not start with number, eg. /www/4myweb/db (observed on Windows 2000).
If DATABASE_NAME is set to something like '/Users/yourname/Sites/mydjangoproject/db/db', make sure you've created the 'db' directory first.
Make sure your /tmp directory is world-writable (an unlikely cause as other thing on your system will also not work). ls /tmp -ald should produce drwxrwxrwt ....
Make sure the path to the database specified in settings.py is a full path.
Also make sure the file is present where you expect it to be.
git clone --depth 1 --branch <tag_name> <repo_url>
Example
git clone --depth 1 --branch 0.37.2 https://github.com/apache/incubator-superset.git
<tag_name> : 0.37.2
<repo_url> : https://github.com/apache/incubator-superset.git
You could use streams in Java 8. To always get 10 entries at the most, you could do:
dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());
One more way of getting minutes and hours is by using SimpleDateFormat.
SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())
SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())
This version should work:
DELETE WorkRecord2
FROM WorkRecord2
INNER JOIN Employee ON EmployeeRun=EmployeeNo
Where Company = '1' AND Date = '2013-05-06'
When doing;
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.
Your other example though;
a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
should work well if you just have the permission on a.txt
. You may want to use a raw (r
-prefixed) string though, to make sure your path does not contain any escape characters like \n
that will be translated to special characters.
a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
Install Ananconda packages and within that launch spyder 3 for first time. Then by second time you just click on spyder under anaconda in all programs.
Rails 6 added an upsert
and upsert_all
methods that deliver this functionality.
Model.upsert(column_name: value)
[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.
Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.
Otherwise, you can use: find_or_initialize_by
or find_or_create_by
, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.
For example, if no user is found with the name "Roger", a new user instance is instantiated with its name
set to "Roger".
user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save
Alternatively, you can use find_or_initialize_by
.
user = User.find_or_initialize_by(name: "Roger")
In Rails 3.
user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save
You can use a block, but the block only runs if the record is new.
User.where(name: "Roger").first_or_initialize do |user|
# this won't run if a user with name "Roger" is found
user.save
end
User.find_or_initialize_by(name: "Roger") do |user|
# this also won't run if a user with name "Roger" is found
user.save
end
If you want to use a block regardless of the record's persistence, use tap
on the result:
User.where(name: "Roger").first_or_initialize.tap do |user|
user.email = "[email protected]"
user.save
end
SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time
When you upgrade to the latest version of the gradle in the gradle-wrapper.properties file
i.e. distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
please do not forget to change the gradle version in the build.gradle file as well
wrapper {
gradleVersion = '6.6.1'
}
class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
ctrls: {
input?: HTMLInputElement;
} = {};
render() {
return (
<input
ref={(input) => this.ctrls.input = input}
value={this.props.value}
onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
/>
);
}
componentDidMount() {
this.ctrls.input.focus();
}
}
put them in an object
Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.
If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
The following code can help you to understand some real world use of predicates (Combined with named iterators).
namespace Predicate
{
class Person
{
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
foreach (Person person in OlderThan(18))
{
Console.WriteLine(person.Age);
}
}
static IEnumerable<Person> OlderThan(int age)
{
Predicate<Person> isOld = x => x.Age > age;
Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };
foreach (Person person in persons)
if (isOld(person)) yield return person;
}
}
}
In my case this was a shopping order. So I disabled the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.
In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order was already submitted and redirected then too.
We can do like:
data = $form.serialize() + "&foo=bar";
For example:
var userData = localStorage.getItem("userFormSerializeData");
var userId = localStorage.getItem("userId");
$.ajax({
type: "POST",
url: postUrl,
data: $(form).serialize() + "&" + userData + "&userId=" + userId,
dataType: 'json',
success: function (response) {
//do something
}
});
With your requirements you don't need BEGIN END
and IF
with unnecessary SELECT
in your trigger. So you can simplify it to this
CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom
FOR EACH ROW
UPDATE BookingRequest
SET status = 1
WHERE idRequest = NEW.idRequest;
Make your life easier by using CSS Selectors
I know I have come late to party but I have a nice suggestion for you.
Using BeautifulSoup
is already been suggested I would rather prefer using CSS Selectors
to scrape data inside HTML
import urllib2
from bs4 import BeautifulSoup
main_url = "http://www.example.com"
main_page_html = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)
# Scrape all TDs from TRs inside Table
for tr in main_page_soup.select("table.class_of_table"):
for td in tr.select("td#id"):
print(td.text)
# For acnhors inside TD
print(td.select("a")[0].text)
# Value of Href attribute
print(td.select("a")[0]["href"])
# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
return page
except Exception:
while 1:
print("Trying again the URL:")
print(passed_url)
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
print("-------------------------------------")
print("---- URL was successfully scraped ---")
print("-------------------------------------")
return page
except Exception:
time.sleep(20)
continue
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
On *nix, you likely have the "whereis" command, which searches your $PATH looking for a binary with a given name. If $0 doesn't contain the full path name, running whereis $scriptname and saving the result into a variable should tell you where the script is located.
Try the steps in here: If you don't have Visual Studio 2010 installed, some icons are provided.
http://supunlivera.blogspot.com/2012/09/visual-studio-2012-theme-change-get-vs.html
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)
I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".
If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
Assuming no key contains either ','
or ':'
:
Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
final String[] parts = entry.split(":");
assert(parts.length == 2) : "Invalid entry: " + entry;
map.put(parts[0], new Integer(parts[1]));
}
JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.
For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.
This project has been tested with Xcode 10 and Swift 4.2.
It can be just a Single View App.
Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell
. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
}
We will connect this outlet later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
Notes
UICollectionViewDataSource
and UICollectionViewDelegate
are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout
protocol to change the size of the views programmatically, but it isn't necessary.Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.
Make sure that your defaults in the Attribute Inspector are also
The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.
Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell"
in ViewController.swift.
And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell
, our custom class that we made.
myLabel
in the MyCollectionViewCell
class. (You can Control-drag.)delegate
and dataSource
to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.
The example above works but it is rather ugly. Here are a few things you can play with:
Background color
In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.
Cell spacing
Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.
Cell shape
If you want rounded corners, a border, and the like, you can play around with the cell layer
. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan
in code above.
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
See this answer for other things you can do with the layer (shadow, for example).
Changing the color when tapped
It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController
class:
// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.cyan
}
Here is the updated look:
Find below code to get database connection from your web app server. Just create datasource in app server and use following code to get connection :
// To Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/abcd");
// Get Connection and Statement
Connection c = ds.getConnection();
stmt = c.createStatement();
Import naming and sql classes. No need to add any xml file or to edit anything in project.
That's it..
Yet another functional solution for Python 2:
from functools import partial
map(partial(map, int), T1)
Python 3 will be a little bit messy though:
list(map(list, map(partial(map, int), T1)))
we can fix this with a wrapper
def oldmap(f, iterable):
return list(map(f, iterable))
oldmap(partial(oldmap, int), T1)
A slight modification of this to change the \voffset
works for me:
\newenvironment{changemargin}[1]{
\begin{list}{}{
\setlength{\voffset}{#1}
}
\item[]}{\end{list}}
And then put your figures in a \begin{changemargin}{-1cm}...\end{changemargin}
environment.
We can read website html content as below :
from urllib.request import urlopen
response = urlopen('http://google.com/')
html = response.read()
print(html)
if (!json[0]) alert("JSON empty");
<div *ngFor="let number of [].constructor(myCollection)">
<div>
Hello World
</div>
</div>
This is a nice and quick way to repeat for the amount of times in myCollection.
So if myCollection was 5, Hello World would be repeated 5 times.
I met the the same error as you.that is because i had transplanted my python file from D disk to e disk. after that ,when I inputed python ,it worked. pip and other exe file which has the same path as pip ,it did not work. when "python -m pip install --upgrade pip" order was inputed,pip order worked,but other exe file which has the same path as pip did not work,so i think it is not the best way. at last I unistalled my python,and re-install it.everything is okay.maybe it is not the best way for all of you ,but it is for me.
Turns out that to copy a complete directory structure gulp
needs to be provided with a base for your gulp.src()
method.
So gulp.src( [ files ], { "base" : "." })
can be used in the structure above to copy all the directories recursively.
If, like me, you may forget this then try:
gulp.copy=function(src,dest){
return gulp.src(src, {base:"."})
.pipe(gulp.dest(dest));
};
Well you have to grab the client for that (surprise), you can either go the simple way:
var io = io.listen(server);
io.clients[sessionID].send()
Which may break, I doubt it, but it's always a possibility that io.clients
might get changed, so use the above with caution
Or you keep track of the clients yourself, therefore you add them to your own clients
object in the connection
listener and remove them in the disconnect
listener.
I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}}
might do the job.
Good question.
@@IDENTITY
: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT
, and the trigger executes another INSERT
statement).
SCOPE_IDENTITY()
: returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).
IDENT_CURRENT()
: returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT
, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).
IDENTITY()
: used when declaring a column in a table as an identity column.
For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.
To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY()
.
This is a variation of the anwser by Muhammad Rehan Saeed, with the class getting parasitically attached to the existing .net core MVC class of the same name, so that everything just works.
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static partial class UrlHelperExtensions
{
/// <summary>
/// Generates a fully qualified URL to an action method by using the specified action name, controller name and
/// route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
/// <summary>
/// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
/// virtual (relative) path to an application absolute path.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="contentPath">The content path.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteContent(
this IUrlHelper url,
string contentPath)
{
HttpRequest request = url.ActionContext.HttpContext.Request;
return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
}
/// <summary>
/// Generates a fully qualified URL to the specified route by using the route name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteRouteUrl(
this IUrlHelper url,
string routeName,
object routeValues = null)
{
return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
}
}
You can let the user set a read-only property by providing it through the constructor:
public class Person
{
public Person(int id)
{
this.Id = id;
}
public string Name { get; set; }
public int Id { get; private set; }
public int Age { get; set; }
}
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
Another, admittedly pretty brute way is to just re-create the branch:
git fetch remote
git branch -f localbranch remote/remotebranch
This throws away the local outdated branch and re-creates one with the same name, so use with care ...
If you are using Maven:
mvn -Dexec.args="-Duser.timezone=Europe/Sofia ....."
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
String UserID = txtUserID.getText().toString();
if (UserID.equals(""))
{
Log.d("value","null");
}
You will see the message in LogCat....
I tried several of these approaches, but none worked properly.
I found this two-step approach on the site Windows Command Line:
forfiles /P %pathtofolder% /M * /C "cmd /c if @isdir==FALSE del @file"
forfiles /P %pathtofolder% /M * /C "cmd /c if @isdir==TRUE rmdir /S /Q @file"
It worked exactly as I needed and as specified by the OP.
server.xml is created when you publish a project.Now If you add more dependency later then server.xml will not be able to catch it until and unless it is refreshed again. Sometimes you need to rebuild context/config file also. First you try to clean the work directory.If it doesn't work then delete server and Server folder,then reconfigure those two.
Get Username and password
Make it more clear to read but put it on a better position over the screen
#!/bin/bash
clear
echo
echo
echo
counter=0
unset username
prompt=" Enter Username:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
if [[ $char == $'\0' ]]; then
break
elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
prompt=$'\b \b'
username="${username%?}"
counter=$((counter-1))
elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
prompt=''
continue
else
counter=$((counter+1))
prompt="$char"
username+="$char"
fi
done
echo
unset password
prompt=" Enter Password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
if [[ $char == $'\0' ]]; then
break
elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
prompt=$'\b \b'
password="${password%?}"
counter=$((counter-1))
elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
echo
prompt=" Enter Password:"
continue
else
counter=$((counter+1))
prompt='*'
password+="$char"
fi
done
I was having the same problem posted in this title. Java would work, but javac
would not in the Windows command prompt (cmd.exe
).
For me, it was simply that I had placed a space when adding C:\Program Files\Java\jdk1.8.0\bin
to the end of my %PATH%
environment variable.
Remove the space between the ;
and the next file path.
This is a hack I'm using:
You can use java
's autocomplete like this:
java -cp path_to.jar <Tab>
This will give you a list of classes available to pass as the starting class. Of course, trying to use one that has no main file will not do anything, but you can see what java
thinks the classes inside the .jar
are called.
The angle between each of your points is going to be 2Pi/x
so you can say that for points n= 0 to x-1
the angle from a defined 0 point is 2nPi/x
.
Assuming your first point is at (r,0)
(where r is the distance from the centre point) then the positions relative to the central point will be:
rCos(2nPi/x),rSin(2nPi/x)
If you are on php 5.4+, it is cleaner to use session_status():
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED
if sessions are disabled.PHP_SESSION_NONE
if sessions are enabled, but none exists.PHP_SESSION_ACTIVE
if sessions are enabled, and one exists.Use Natural Text Editing preset!
Essentially it binds, among other key sequences, Option + LeftArrow to ^[b
sequence and Option + RightArrow to ^[f
This works in fish and bash, as well as in psql terminal.
I recommend setting an alternative location for your npm modules.
npm config set prefix C:\Dev\npm-repository\npm --global
npm config set cache C:\Dev\npm-repository\npm-cache --global
Of course you can set the location to wherever best suits.
This has worked well for me and gets around any permissions issues that you may encounter.
This has been working for me:
1. Set credential hepler to store
$ git config --global credential.helper store
2. then verify if you want:
$ git config --global credential.helper
store
Simple example when using git bash quoted from Here (works for current repo only, use --global
for all repos)
$ git config credential.helper store
$ git push http://example.com/repo.git
Username: < type your username >
Password: < type your password >
[several days later]
$ git push http://example.com/repo.git
[your credentials are used automatically]
Will work for VS Code too.
More detailed example and advanced usage here.
Note: Username & Passwords are not encrypted and stored in plain text format so use it on your personal computer only.
.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.
For Example: 1D ARRAY:
d=np.array([1,2,3,4])
print(d)
(1,)
Output: (4,) ie the number4 denotes the no of elements in the 1D Array.
2D Array:
e=np.array([[1,2,3],[4,5,6]])
print(e)
(2,3)
Output: (2,3) ie the number of rows and the number of columns.
The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.
If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.
static Logger log = Logger.getLogger(MyClass.class);
Thanks,
I had the same problem. Docker running but couldn't access it through CLI.
For me the problem was solved by executing "Docker Quickstart Terminal.app". This is located in the "/Applications/Docker/" folder. As long as I work in this instance of the Terminal app Docker works perfectly. If a second window is needed I have to run the "Quickstart" app once more.
I have a Docker for Mac installation. Therefore I am not sure if my solution is valid for a Homebrew installation.
The "Docker Quickstart Terminal" app seems to be essentially some applescripts to launch the terminal app and a bash start script that initialise all the necessary environment variables.
Hope this helps someone else !
Solutions listed did not exactly work for me. The closest was Chief Wiggum - I wanted to add a comment on his answer but lack the reputation to do so. So I post as separate answer:
=MIN(IF(A1:E1>0;A1:E1))
Then instead of pressing ENTER, press CTRL+SHIFT+ENTER and watch Excel add {
and }
to respectively the beginning and the end of the formula (to activate the formula on array).
The comma "," and "If" statement as proposed by Chief Wiggum did not work on Excel Home and Student 2013. Need a semicolon ";" as well as full cap "IF" did the trick. Small syntax difference but took me 1.5 hour to figure out why I was getting an error and #VALUE.
Move semantics are based on rvalue references.
An rvalue is a temporary object, which is going to be destroyed at the end of the expression. In current C++, rvalues only bind to const
references. C++1x will allow non-const
rvalue references, spelled T&&
, which are references to an rvalue objects.
Since an rvalue is going to die at the end of an expression, you can steal its data. Instead of copying it into another object, you move its data into it.
class X {
public:
X(X&& rhs) // ctor taking an rvalue reference, so-called move-ctor
: data_()
{
// since 'x' is an rvalue object, we can steal its data
this->swap(std::move(rhs));
// this will leave rhs with the empty data
}
void swap(X&& rhs);
// ...
};
// ...
X f();
X x = f(); // f() returns result as rvalue, so this calls move-ctor
In the above code, with old compilers the result of f()
is copied into x
using X
's copy constructor. If your compiler supports move semantics and X
has a move-constructor, then that is called instead. Since its rhs
argument is an rvalue, we know it's not needed any longer and we can steal its value.
So the value is moved from the unnamed temporary returned from f()
to x
(while the data of x
, initialized to an empty X
, is moved into the temporary, which will get destroyed after the assignment).
You can batch change schemas of multiple database objects as described in this post:
How to change schema of all tables, views and stored procedures in MSSQL
try this
let when = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: when) {
//some code
}
On technologies with message loops (not sure if ASP is one of them), you can block the loop and process messages until the task is over, and use ContinueWith to unblock the code:
public void WaitForTask(Task task)
{
DispatcherFrame frame = new DispatcherFrame();
task.ContinueWith(t => frame.Continue = false));
Dispatcher.PushFrame(frame);
}
This approach is similar to blocking on ShowDialog and still keeping the UI responsive.
On top of @mise's answer, After I installed MacOS Mojave, I also had to change files ownership on all my MAMP directory and contents).
From the Finder, I went in Application/MAMP
, showed files info (cmd
+ i
) and in permissions section added myself with read & write perms, then from the little gear applied to all the children.
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
An instance of Date always represents a date and cannot be empty. You can use a null value of date2 to represent "there is no date". You will have to check for null whenever you use date2 to avoid a NullPointerException, like when rendering your page:
if (date2 != null)
// print date2
else
// print nothing, or a default value
The best and simple way:
Convert(varchar, {EndTime} - {StartTime}, 108)
Just like Anri noted.
Returning false
from the function will stop the event continuing. I.e. it will stop the form submitting.
i.e.
function someFunction()
{
if (allow) // For example, checking that a field isn't empty
{
return true; // Allow the form to submit
}
else
{
return false; // Stop the form submitting
}
}
Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:
message.max.bytes
and replica.fetch.max.bytes
. message.max.bytes
has to be equal or smaller(*) than replica.fetch.max.bytes
.max.request.size
to send the larger message.max.partition.fetch.bytes
to receive larger messages.(*) Read the comments to learn more about message.max.bytes
<=replica.fetch.max.bytes
Try using:
.button input, .button a {
// css stuff
}
Also, read up on CSS.
Edit: If it were me, I'd add the button class to the element, not to the parent tag. Like so:
HTML:
<a href="#" class='button'>BUTTON TEXT</a>
<input type="submit" class='button' value='buttontext' />
CSS:
.button {
// css stuff
}
For specific css stuff use:
input.button {
// css stuff
}
a.button {
// css stuff
}
Also, Make sure the "Copy always" option is selected for [log4net].config
There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.
If you have a long running background work you should specify this by using the correct Task Option.
You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.
Try to use datepicker/ timepicker instead of datetimepicker like:
replace:
$('#datetimepicker1').datetimepicker();
with:
$('#datetimepicker1').datepicker(); // or timepicker for time picker
The rules (which did not change in C++11):
std
namespace is reserved. (You are allowed to add template specializations, though.) From the 2003 C++ Standard:
17.4.3.1.2 Global names [lib.global.names]
Certain sets of names and function signatures are always reserved to the implementation:
- Each name that contains a double underscore (
__
) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.- Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165
165) Such names are also reserved in namespace
::std
(17.4.3.1).
Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:
7.1.3 Reserved identifiers
Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
- All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
- Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
- All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
- Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.
No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.
If the program removes (with
#undef
) any macro definition of an identifier in the first group listed above, the behavior is undefined.154) The list of reserved identifiers with external linkage includes
errno
,math_errhandling
,setjmp
, andva_end
.
Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:
E
followed a digit or uppercase letter:
is
or to
followed by a lowercase letter
LC_
followed by an uppercase letter
f
or l
are reserved
SIG
followed by an uppercase letter are reserved
SIG_
followed by an uppercase letter are reserved
str
, mem
, or wcs
followed by a lowercase letter are reserved
PRI
or SCN
followed by any lowercase letter or X
are reserved
_t
are reserved
While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.
Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.
After doing research on this article I no longer end my identifiers with _t
as this is reserved by the POSIX standard.
The rule about any identifier ending with _t
surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.
CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.
You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.
Something as simple as [a-z]+
, or perhaps [\S]+
, or even [a-zA-Z]+
?
Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.
As of 2.6, set.intersection
takes arbitrarily many iterables.
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])
If you click on the title CSS (SCSS)
in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
In my case, I just had to put the element one line down:
This throws an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}> {props.children}
</TouchableWithoutFeedback>;
}
_x000D_
While this does not throw an error:
export function DismissKeyboard(props: IProps) {
return <TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}>
{props.children}
</TouchableWithoutFeedback>;
}
_x000D_
Like this.
SELECT DISTINCT COL_NAME FROM myTable WHERE COL_NAME iLIKE '%Priceorder%'
In postgresql.
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
Carbon has a bunch of comparison functions with mnemonic names:
Usage:
if($model->edited_at->greaterThan($model->created_at)){
// edited at is newer than created at
}
Valid for nesbot/carbon 1.36.2
if you are not sure what Carbon version you are on, run this
$composer show "nesbot/carbon"
documentation: https://carbon.nesbot.com/docs/#api-comparison
So we are all doing the same home work?
Strange how the most up-voted answer is wrong. Remember, draw/fillOval take height and width as parameters, not the radius. So to correctly draw and center a circle with user-provided x, y, and radius values you would do something like this:
public static void drawCircle(Graphics g, int x, int y, int radius) {
int diameter = radius * 2;
//shift x and y by the radius of the circle in order to correctly center it
g.fillOval(x - radius, y - radius, diameter, diameter);
}
You can reuse your confirm:
function doConfirm(body, $_nombrefuncion)
{ var param = undefined;
var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
autoOpen: false,
buttons: {
Yes: function() {
param = true;
$_nombrefuncion(param);
$(this).dialog('close');
},
No: function() {
param = false;
$_nombrefuncion(param);
$(this).dialog('close');
}
}
});
$confirm.html("<h3>"+body+"<h3>");
$confirm.dialog('open');
};
// for this form just u must change or create a new function for to reuse the confirm
function resultadoconfirmresetVTyBFD(param){
$fecha = $("#asigfecha").val();
if(param ==true){
// DO THE CONFIRM
}
}
//Now just u must call the function doConfirm
doConfirm('body message',resultadoconfirmresetVTyBFD);
In my case it was permission issue. Open application folder properties -> Security tab -> Edit -> Add
You can validate a TypeScript type at runtime using ts-validate-type, like so (does require a Babel plugin though):
const user = validateType<{ name: string }>(data);
Selenium answers this question in their DESCRIPTION.rst file:
Drivers
=======Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires
geckodriver <https://github.com/mozilla/geckodriver/releases>
_, which needs to be installed before the below examples can be run. Make sure it's in yourPATH
, e. g., place it in/usr/bin
or/usr/local/bin
.
Failure to observe this step will give you an error `selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
Basically just download the geckodriver, unpack it and move the executable to your /usr/bin folder.
You can loop over recipientce like:
foreach (['[email protected]', '[email protected]'] as $recipient) {
Mail::to($recipient)->send(new OrderShipped($order));
}
See documentation here
I solved my issue using the following command :
conda install opencv
this can be done this way
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
You can load the whole *.dll assembly with
$Assembly = [System.Reflection.Assembly]::LoadFrom("C:\folder\file.dll");
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
Why not use a media query range.
I'm currently working on a responsive layout for my employer and the ranges I'm using are as follows:
You have your main desktop styles in the body of the CSS file (1024px and above) and then for specific screen sizes I'm using:
@media all and (min-width:960px) and (max-width: 1024px) {
/* put your css styles in here */
}
@media all and (min-width:801px) and (max-width: 959px) {
/* put your css styles in here */
}
@media all and (min-width:769px) and (max-width: 800px) {
/* put your css styles in here */
}
@media all and (min-width:569px) and (max-width: 768px) {
/* put your css styles in here */
}
@media all and (min-width:481px) and (max-width: 568px) {
/* put your css styles in here */
}
@media all and (min-width:321px) and (max-width: 480px) {
/* put your css styles in here */
}
@media all and (min-width:0px) and (max-width: 320px) {
/* put your css styles in here */
}
This will cover pretty much all devices being used - I would concentrate on getting the styling correct for the sizes at the end of the range (i.e. 320, 480, 568, 768, 800, 1024) as for all the others they will just be responsive to the size available.
Also, don't use px anywhere - use em's or %.
Step 1: Install Visual C++ 2010 Express from here.
(Do not install Microsoft Visual Studio 2010 Service Pack 1 )
Step 2: Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.
Step 3: Install offline version of Windows SDK for Visual Studio 2010 (v7.1) from here. This is required for 64bit extensions. Windows has builtin mounting for ISOs like Pismo.
Step 4: You need to install the ISO file with Pismo File Mount Audit Package. Download Pismo from here
Step 5: Right click the downloaded ISO file and choose mount with Pismo. Thereafter, install the Setup\SDKSetup.exe instead of setup.exe.
Step 6a: Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 by changing directory to C:\Program Files (x86)\Microsoft Visual Studio version\VC\ on the command prompt.
Type command on the command prompt:
cd C:\Program Files (x86)\Microsoft Visual Studio version\VC\r
Step 6b:
To configure this Command Prompt window for 64-bit command-line builds that target x86 platforms, at the command prompt, enter:
vcvarsall x86
Click here for more options.
Step 7: At the command prompt, install the PyCrypto by typing:
C:\Python3X>pip install -U your_wh_file
Capslock + Tab to indent multiple lines at once. Highlight the text first.
Tried above steps, didn't work on Ubuntu 20. For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update && sudo apt install yarn
Maybe you want to use twill. It's quite easy to use and should be able to do what you want.
It will look like the following:
from twill.commands import *
go('http://example.org')
fv("1", "email-email", "blabla.com")
fv("1", "password-clear", "testpass")
submit('0')
You can use showforms()
to list all forms once you used go…
to browse to the site you want to login. Just try it from the python interpreter.
I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best
Since I'm the current world record holder for the most digits of pi, I'll add my two cents:
Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.
In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/
But when you get into world-record territory, there's nothing to compare against.
Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.
This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.
Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:
These are both O(N log(N)^2)
algorithms that were fairly easy to implement.
However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):
This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.
Then we verify the binary digits using the BBP formulas for digit extraction.
This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.
The advantage of this is:
The disadvantage is:
I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.
Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.
So I've pulled this snippet from my blog:
N = # of decimal digits desired
p = 64-bit prime number
Compute A using base 10 arithmetic and B using binary arithmetic.
If A = B
, then with "extremely high probability", the conversion is correct.
For further reading, see my blog post Pi - 5 Trillion Digits.
This may not have been the case at the time the question was asked, but as of Chrome 66, autoplay is blocked.
http://bgr.com/2018/04/18/google-chrome-66-download-auto-playing-videos-block/
creating or moving some/all reference containing worksheets (out and) into your workbook may solve it.
I had this issue after copying some sheets from "template" sheets/workbooks to some new "destination" workbook (the templates were provided by other users!):
I got:
project
on A1
)WbTempl2.Names("project").refersTo="C:\WbTempl1.xls]'WsTempl1RefDef!A1"
=project
)and wanted to create a WbDst to copy WsTempl1RefDef and WsTempl2RefUsr into it.
The following did not work:
Here as well the Ctrl(SHIFT)ALTF9 nor Application.CalculateFullRebuild
worked on WbDst.
The following worked:
One point missed in the existing answers is show how to inherit the error traps. The bash
shell provides one such option for that using set
-E
If set, any trap on
ERR
is inherited by shell functions, command substitutions, and commands executed in a subshell environment. TheERR
trap is normally not inherited in such cases.
Adam Rosenfield's answer recommendation to use set -e
is right in certain cases but it has its own potential pitfalls. See GreyCat's BashFAQ - 105 - Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?
According to the manual, set -e exits
if a simple commandexits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a
while
oruntil
keyword, part of thetest in a if statement
, part of an&&
or||
list except the command following thefinal && or ||
,any command in a pipeline but the last
, or if the command's return value is being inverted via!
".
which means, set -e
does not work under the following simple cases (detailed explanations can be found on the wiki)
Using the arithmetic operator let
or $((..))
( bash
4.1 onwards) to increment a variable value as
#!/usr/bin/env bash
set -e
i=0
let i++ # or ((i++)) on bash 4.1 or later
echo "i is $i"
If the offending command is not part of the last command executed via &&
or ||
. For e.g. the below trap wouldn't fire when its expected to
#!/usr/bin/env bash
set -e
test -d nosuchdir && echo no dir
echo survived
When used incorrectly in an if
statement as, the exit code of the if
statement is the exit code of the last executed command. In the example below the last executed command was echo
which wouldn't fire the trap, even though the test -d
failed
#!/usr/bin/env bash
set -e
f() { if test -d nosuchdir; then echo no dir; fi; }
f
echo survived
When used with command-substitution, they are ignored, unless inherit_errexit
is set with bash
4.4
#!/usr/bin/env bash
set -e
foo=$(expr 1-1; true)
echo survived
when you use commands that look like assignments but aren't, such as export
, declare
, typeset
or local
. Here the function call to f
will not exit as local
has swept the error code that was set previously.
set -e
f() { local var=$(somecommand that fails); }
g() { local var; var=$(somecommand that fails); }
When used in a pipeline, and the offending command is not part of the last command. For e.g. the below command would still go through. One options is to enable pipefail
by returning the exit code of the first failed process:
set -e
somecommand that fails | cat -
echo survived
The ideal recommendation is to not use set -e
and implement an own version of error checking instead. More information on implementing custom error handling on one of my answers to Raise error in a Bash script
I solved this by doing the following:
WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters
Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.
.mydiv {
...
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
...
}
Adapted from: MDN
[Required(ErrorMessage = "Please enter Social Email id")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-
openssl rsa -noout -text -inform PEM -in key.pub -pubin
or for the private key file, this:-
openssl rsa -noout -text -in key.private
which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)
You can convert like this.
date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
Integers are trivial; this you already know. The deep problem is how to deal with floating-point values. At that point, you've got to know a bit more about how floating point values actually work.
The key is Double.doubleToLongBits(), which lets you get at the IEEE representation of the number. (The method's really a direct cast under the hood, with a bit of magic for dealing with NaN values.) Once a double has been converted to a long, you can just use 0x8000000000000000L as a mask to select the sign bit; if zero, the value is positive, and if one, it's negative.
I done in this way
from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy
# To save model
model.save('my_model_01.hdf5')
# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}
# To load a persisted model that uses the CRF layer
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)
For big zip files for deployment, I use quarter hours. No one else on this page had mentioned it before, so I'll put my small script here:
set /a "quarter_hours=%time:~0,2%*4 + %time:~3,2% / 15"
set "zip_file=release_%DATE:~-4%.%DATE:~4,2%.%DATE:~7,2%.%quarter_hours%.zip"
It doesn't zero pad quarter hours from midnight to 5am yet, but it still makes it so you can have a stamped release multiple times a day with few collisions.
Hope that helps.
Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).
A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.
You declare that one class is subclass of another via the "extends" keyword in Java.
public class B extends A
{
...
}
B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.
This is the main concept of inheritance in Object-Oriented programming.
Go to
C:\Program Files\MySQL\MySQL Server 5.2\bin
then Open MySQLInstanceConfig file
then complete the wizard.
Click finish
Solve the problem
I think this is the best way to change the port number also.
It works for me
Another way that works with the YAML parser used in Jekyll:
title: My Life: A Memoir
Colons not followed by spaces don't seem to bother Jekyll's YAML parser, on the other hand. Neither do dashes.
I think restful authentication involves the passing of an authentication token as a parameter in the request. Examples are the use of apikeys by api's. I don't believe the use of cookies or http auth qualifies.
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install