Yeah, this is a platform dependent question.
If you are writing a console program on POSIX,
use the signal API (#include <signal.h>
).
In a WIN32 GUI application you should handle the WM_KEYDOWN
message.
Somehow GenerateConsoleCtrlEvent()
return error if you call it for another process, but you can attach to another console application and send event to all child processes.
void SendControlC(int pid)
{
AttachConsole(pid); // attach to process console
SetConsoleCtrlHandler(NULL, TRUE); // disable Control+C handling for our app
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // generate Control+C event
}
if you get this error
Gradle:
FAILURE: Could not determine which tasks to execute.
* What went wrong:
Task 'assemble' not found in root project 'MyProject'.
* Try:
Run gradle tasks to get a list of available tasks.
You need to edit your Projects .iml file. not the one under src. the one that is like myappProject.iml' delete the whole component name = facetmanager
<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
...remove this element and everything inside such as <facet> elements...
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
...keep this part...
</component
If anyone is coming from React-world, I ended up solving my use-case using a combination of history
-library, useEffect and localStorage
When user selects new project:
function selectProject(customer_id: string, project_id: string){
const projectUrl = `/customer/${customer_id}/project/${project_id}`
localStorage.setItem("selected-project", projectUrl)
history.push(projectUrl)
}
When user comes back from another website. If there's something in localStorage, send him there.
useEffect(() => {
const projectUrl = localStorage.getItem("selected-project")
if (projectUrl) {
history.push(projectUrl)
}
}, [history])
When user has exited a project, empty localStorage
const selectProject = () => {
localStorage.removeItem("selected-project")
history.push("/")
}
Consider these filenames:
C:\temp\file.txt
- This is a path, an absolute path, and a canonical path.
.\file.txt
- This is a path. It's neither an absolute path nor a canonical path.
C:\temp\myapp\bin\..\\..\file.txt
- This is a path and an absolute path. It's not a canonical path.
A canonical path is always an absolute path.
Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt
becomes c:/temp/file.txt
). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\
and resolving symlinks (on unixes).
Also note the following example with nio.Paths:
String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";
System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());
While both paths refer to the same location, the output will be quite different:
C:\Windows
C:\Windows\System32\drivers
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
The other answers address the main thrust of the question, but just to comment on this part...
PS C:\> [array]$foo = @("bar") PS C:\> $foo -eq $null PS C:\>
How can "-eq $null" give no results? It's either $null or it's not.
It's confusing at first, but that is giving you the result of $foo -eq $null
, it's just that the result has no displayable representation.
Since $foo
holds an array, $foo -eq $null
means "return an array containing the elements of $foo
that are equal to $null
". Are there any elements of $foo
that are equal to $null
? No, so $foo -eq $null
should return an empty array. That's exactly what it does, the problem is that when an empty array is displayed at the console you see...nothing...
PS> @()
PS>
The array is still there, even if you can't see its elements...
PS> @().GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @().Length
0
We can use similar commands to confirm that $foo -eq $null
is returning an array that we're not able to "see"...
PS> $foo -eq $null
PS> ($foo -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($foo -eq $null).Length
0
PS> ($foo -eq $null).GetValue(0)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($foo -eq $null).GetValue(0)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
Note that I am calling the Array.GetValue
method instead of using the indexer (i.e. ($foo -eq $null)[0]
) because the latter returns $null
for invalid indices and there's no way to distinguish them from a valid index that happens to contain $null
.
We see similar behavior if we test for $null
in/against an array that contains $null
elements...
PS> $bar = @($null)
PS> $bar -eq $null
PS> ($bar -eq $null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> ($bar -eq $null).Length
1
PS> ($bar -eq $null).GetValue(0)
PS> $null -eq ($bar -eq $null).GetValue(0)
True
PS> ($bar -eq $null).GetValue(0) -eq $null
True
PS> ($bar -eq $null).GetValue(1)
Exception calling "GetValue" with "1" argument(s): "Index was outside the bounds of the array."
At line:1 char:1
+ ($bar -eq $null).GetValue(1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IndexOutOfRangeException
In this case, $bar -eq $null
returns an array containing one element, $null
, which has no visual representation at the console...
PS> @($null)
PS> @($null).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS> @($null).Length
1
private static Form IsFormAlreadyOpen(Type formType)
{
return Application.OpenForms.Cast<Form>().FirstOrDefault(openForm => openForm.GetType() == formType);
}
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020
The error says that FormGroup is not recognized in this module. So You have to import these(below) modules in every module that uses FormGroup
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
Then add FormsModule and ReactiveFormsModule into your Module's imports array.
imports: [
FormsModule,
ReactiveFormsModule
],
You may be thinking that I have already added it in AppModule and it should inherit from it? But it is not. because these modules are exporting required directives that are available only in importing modules. Read more here... https://angular.io/guide/sharing-ngmodules.
Other factors for these errors may be spell error like below...
[FormGroup]="form" Capital F instead of small f
[formsGroup]="form" Extra s after form
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
This will display the date and time
var resizeHandle = document.getElementById('resizable');_x000D_
var box = document.getElementById('resize');_x000D_
resizeHandle.addEventListener('mousedown', initialiseResize, false);_x000D_
_x000D_
function initialiseResize(e) {_x000D_
window.addEventListener('mousemove', startResizing, false);_x000D_
window.addEventListener('mouseup', stopResizing, false);_x000D_
}_x000D_
_x000D_
function stopResizing(e) {_x000D_
window.removeEventListener('mousemove', startResizing, false);_x000D_
window.removeEventListener('mouseup', stopResizing, false);_x000D_
}_x000D_
_x000D_
function startResizing(e) {_x000D_
box.style.width = (e.clientX) + 'px';_x000D_
box.style.height = (e.clientY) + 'px';_x000D_
}_x000D_
_x000D_
function startResizing(e) {_x000D_
box.style.width = (e.clientX - box.offsetLeft) + 'px';_x000D_
box.style.height = (e.clientY - box.offsetTop) + 'px';_x000D_
}
_x000D_
#resize {_x000D_
position: relative;_x000D_
width: 130px;_x000D_
height: 130px;_x000D_
border: 2px solid blue;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
#resizable {_x000D_
background-color: white;_x000D_
width: 10px;_x000D_
height: 10px;_x000D_
cursor: se-resize;_x000D_
position: absolute;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
}
_x000D_
<div id="resize">_x000D_
_x000D_
<div id="resizable">_x000D_
</div>
_x000D_
Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.
toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
I found that this publication referenced in an answer to a previous similar question. It is very helpful:
http://cadik.posvete.cz/color_to_gray_evaluation/
It shows 'tons' of different methods to generate grayscale images with different outcomes!
Its a bit late, however... Full implementation:
[HttpGet]
public async Task<HttpResponseMessage> GetPageFromUriOrBody(RequestQuery requestQuery)
{
log(nameof(GetPageFromUriOrBody), nameof(requestQuery));
var responseResult = await _requestQueryCache.GetOrCreate(
nameof(GetPageFromUriOrBody)
, requestQuery
, (x) => getPageContent(x).Result);
return Request.CreateResponse(System.Net.HttpStatusCode.Accepted, responseResult);
}
static MemoryCacheWithPolicy<RequestQuery, string> _requestQueryCache = new MemoryCacheWithPolicy<RequestQuery, string>();
Here is getPageContent
signature:
async Task<string> getPageContent(RequestQuery requestQuery);
And here is the MemoryCacheWithPolicy
implementation:
public class MemoryCacheWithPolicy<TParameter, TResult>
{
static ILogger _nlogger = new AppLogger().Logger;
private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions()
{
//Size limit amount: this is actually a memory size limit value!
SizeLimit = 1024
});
/// <summary>
/// Gets or creates a new memory cache record for a main data
/// along with parameter data that is assocciated with main main.
/// </summary>
/// <param name="key">Main data cache memory key.</param>
/// <param name="param">Parameter model that assocciated to main model (request result).</param>
/// <param name="createCacheData">A delegate to create a new main data to cache.</param>
/// <returns></returns>
public async Task<TResult> GetOrCreate(object key, TParameter param, Func<TParameter, TResult> createCacheData)
{
// this key is used for param cache memory.
var paramKey = key + nameof(param);
if (!_cache.TryGetValue(key, out TResult cacheEntry))
{
// key is not in the cache, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is created.");
}
else
{
// data is chached so far..., check if param model is same (or changed)?
if(!_cache.TryGetValue(paramKey, out TParameter cacheParam))
{
//exception: this case should not happened!
}
if (!cacheParam.Equals(param))
{
// request param is changed, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is re-created (param model has been changed).");
}
else
{
_nlogger.Trace(" cache is used.");
}
}
return await Task.FromResult<TResult>(cacheEntry);
}
MemoryCacheEntryOptions createMemoryCacheEntryOptions(TimeSpan slidingOffset, TimeSpan relativeOffset)
{
// Cache data within [slidingOffset] seconds,
// request new result after [relativeOffset] seconds.
return new MemoryCacheEntryOptions()
// Size amount: this is actually an entry count per
// key limit value! not an actual memory size value!
.SetSize(1)
// Priority on removing when reaching size limit (memory pressure)
.SetPriority(CacheItemPriority.High)
// Keep in cache for this amount of time, reset it if accessed.
.SetSlidingExpiration(slidingOffset)
// Remove from cache after this time, regardless of sliding expiration
.SetAbsoluteExpiration(relativeOffset);
//
}
void createMemoryCache(object key, TResult cacheEntry, object paramKey, TParameter param)
{
// Cache data within 2 seconds,
// request new result after 5 seconds.
var cacheEntryOptions = createMemoryCacheEntryOptions(
TimeSpan.FromSeconds(2)
, TimeSpan.FromSeconds(5));
// Save data in cache.
_cache.Set(key, cacheEntry, cacheEntryOptions);
// Save param in cache.
_cache.Set(paramKey, param, cacheEntryOptions);
}
void checkCacheEntry<T>(object key, string name)
{
_cache.TryGetValue(key, out T value);
_nlogger.Fatal("Key: {0}, Name: {1}, Value: {2}", key, name, value);
}
}
nlogger
is just nLog
object to trace MemoryCacheWithPolicy
behavior.
I re-create the memory cache if request object (RequestQuery requestQuery
) is changed through the delegate (Func<TParameter, TResult> createCacheData
) or re-create when sliding or absolute time reached their limit. Note that everything is async too ;)
In PySpark(python) one of the option is to have the column in unix_timestamp format.We can convert string to unix_timestamp and specify the format as shown below. Note we need to import unix_timestamp and lit function
from pyspark.sql.functions import unix_timestamp, lit
df.withColumn("tx_date", to_date(unix_timestamp(df_cast["date"], "MM/dd/yyyy").cast("timestamp")))
Now we can apply the filters
df_cast.filter(df_cast["tx_date"] >= lit('2017-01-01')) \
.filter(df_cast["tx_date"] <= lit('2017-01-31')).show()
you can try setting the padding instead of the height/width.
Google does not provide an IP for us to set A record. If it would we could use naked domains.
There is another option, by setting A record to foreign web server's IP and that server could make an http redirect from e.g domain.com to www.domain.com (check out GiDNS)
Changing a constant type will lead to an Undefined Behavior.
However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.
Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.
JAVA_HOME
and JRE_HOME
are not used by Java itself. Some third-party programs (for example Apache Tomcat) expect one of these environment variables to be set to the installation directory of the JDK
or JRE
. If you are not using software that requires them, you do not need to set JAVA_HOME
and JRE_HOME
.
PATH
is an environment variable used by the operating system (Windows, Mac OS X, Linux) where it will look for native executable programs to run. You should add the bin
subdirectory of your JDK
installation directory to the PATH
, so that you can use the javac
and java
commands and other JDK
tools in a command prompt window. Courtesy: coderanch
Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:
$comment = "$_POST['comment']";
Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:
$comment = "$_POST[comment]";
but dropping either pair of quotes works; it's a matter of style I suppose :)
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
Then you could write:
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
I realize this is old but I figured I'd clear up a misconception for other travelers. Setting plt.pyplot.isinteractive()
to False
means that the plot will on be drawn on specific commands to draw (i.e. plt.pyplot.show()
). Setting plt.pyplot.isinteractive()
to True
means that every pyplot
(plt
) command will trigger a draw command (i.e. plt.pyplot.show()
). So what you were more than likely looking for is plt.pyplot.show()
at the end of your program to display the graph.
As a side note you can shorten these statements a bit by using the following import command import matplotlib.pyplot as plt
rather than matplotlib as plt
.
None of the previous answers are complete and most contain misinformation.
There are three ways of accessing the attributes of a DOM Element in JavaScript. All three work reliably in modern browsers as long as you understand how to utilize them.
element.attributes
Elements have a property attributes that returns a live NamedNodeMap of Attr objects. The indexes of this collection may be different among browsers. So, the order is not guaranteed. NamedNodeMap
has methods for adding and removing attributes (getNamedItem
and setNamedItem
, respectively).
Notice that though XML is explicitly case sensitive, the DOM spec calls for string names to be normalized, so names passed to getNamedItem
are effectively case insensitive.
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//you can look up specific attributes_x000D_
var classAttr = div.attributes.getNamedItem('CLASS');_x000D_
document.write('attributes.getNamedItem() Name: ' + classAttr.name + ' Value: ' + classAttr.value + '<br>');_x000D_
_x000D_
//you can enumerate all defined attributes_x000D_
for(var i = 0; i < div.attributes.length; i++) {_x000D_
var attr = div.attributes[i];_x000D_
document.write('attributes[] Name: ' + attr.name + ' Value: ' + attr.value + '<br>');_x000D_
}_x000D_
_x000D_
//create custom attribute_x000D_
var customAttr = document.createAttribute('customTest');_x000D_
customAttr.value = '567';_x000D_
div.attributes.setNamedItem(customAttr);_x000D_
_x000D_
//retreive custom attribute_x000D_
customAttr = div.attributes.getNamedItem('customTest');_x000D_
document.write('attributes.getNamedItem() Name: ' + customAttr.name + ' Value: ' + customAttr.value + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
element.getAttribute
& element.setAttribute
These methods exist directly on the Element
without needing to access attributes
and its methods but perform the same functions.
Again, notice that string name are case insensitive.
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.getAttribute('class') + '<br>');_x000D_
document.write('Name: ID Value: ' + div.getAttribute('ID') + '<br>');_x000D_
document.write('Name: DATA-TEST Value: ' + div.getAttribute('DATA-TEST') + '<br>');_x000D_
document.write('Name: nonStandard Value: ' + div.getAttribute('nonStandard') + '<br>');_x000D_
_x000D_
_x000D_
//create custom attribute_x000D_
div.setAttribute('customTest', '567');_x000D_
_x000D_
//retreive custom attribute_x000D_
document.write('Name: customTest Value: ' + div.getAttribute('customTest') + '<br>');
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
element.id
Many attributes can be accessed using convenient properties on the DOM object. Which attributes exist depends on the DOM node's type, not which attributes are defined in the HTML. The properties are defined somewhere in the prototype chain of DOM object in question. The specific properties defined will depend on the type of Element you are accessing. For example, className
and id
are defined on Element
and exist on all DOM nodes that are elements (ie. not text or comment nodes). But value
is more narrow. It's defined on HTMLInputElement
and may not exist on other elements.
Notice that JavaScript properties are case sensitive. Although most properties will use lowercase, some are camelCase. So always check the spec to be sure.
This "chart" captures a portion of the prototype chain for these DOM objects. It's not even close to complete, but it captures the overall structure.
____________Node___________
| | |
Element Text Comment
| |
HTMLElement SVGElement
| |
HTMLInputElement HTMLSpanElement
var div = document.getElementsByTagName('div')[0];_x000D_
_x000D_
//get specific attributes_x000D_
document.write('Name: class Value: ' + div.className + '<br>');_x000D_
document.write('Name: id Value: ' + div.id + '<br>');_x000D_
document.write('Name: ID Value: ' + div.ID + '<br>'); //undefined_x000D_
document.write('Name: data-test Value: ' + div.dataset.test + '<br>'); //.dataset is a special case_x000D_
document.write('Name: nonStandard Value: ' + div.nonStandard + '<br>'); //undefined
_x000D_
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>
_x000D_
Caveat: This is an explanation of how the HTML spec defines and modern browsers handle attributes. I did not attempt to deal with limitations of ancient, broken browsers. If you need to support old browsers, in addition to this information, you will need to know what is broken in the those browsers.
Techniques I gathered from other answers:
Makes a 0 byte file a very clear, backward-compatible way:
type nul >EmptyFile.txt
idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work
A 0 byte file another way, it's backward-compatible-looking:
REM. >EmptyFile.txt
idea via: Johannes
A 0 byte file 3rd way backward-compatible-looking, too:
echo. 2>EmptyFile.txt
idea via: TheSmurf
A 0 byte file the systematic way probably available since Windows 2000:
fsutil file createnew EmptyFile.txt 0
idea via: Emm
A 0 bytes file overwriting readonly files
ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL
idea via: copyitright
A single newline (2 bytes: 0x0D 0x0A
in hex notation, alternatively written as \r\n
):
echo.>AlmostEmptyFile.txt
Note: no space between echo
, .
and >
.
idea via: How can you echo a newline in batch files?
edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown
TheInvisibleFeature <nul >EmptyFile.txt
A 0 bytes file: invalid command/ with a random name (compatibility: uknown):
%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt
via: great source for random by Hung Huynh
edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command
A 0 bytes file: invalid command/ the funky way (compatibility: unknown)
*>EmptyFile.txt
idea via: Andriy M
A 0 bytes file 4th-coming way:
break > file.txt
idea via: foxidrive thanks to comment of Double Gras!
My simple solution to test if a string is null:
if (s.equals("null")){ ..... }
There are two cases.
The variable (of type String) is null(doesn't exists): == works.
The variable has a null value, *.equals("null") gives te right boolean value.
For a given DateTime, you can add days, hours, minutes, etc. Here's some examples:
$now = new \DateTime();
$now->add(new DateInterval('PT24H')); // adds 24 hours
$now->add(new DateInterval('P2D')); // adds 2 days
PHP: DateTime::add - Manual https://www.php.net/manual/fr/datetime.add.php
Eg:
Datatable newTable = new DataTable();
foreach(string s1 in list)
{
if (s1 != string.Empty) {
dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
foreach(DataRow dr in dvProducts.ToTable().Rows)
{
newTable.ImportRow(dr);
}
}
}
ListView1.DataSource = newTable;
ListView1.DataBind();
The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:
<target name="compile">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
<!-- ^^^^^^^^^^^^^^^^^^^^^^^^^ -->
<classpath>
<path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
<path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
</classpath>
</javac>
</target>
Create a class called Round and try using the method round as Round.round(targetValue, roundToDecimalPlaces) in your code
public class Round {
public static float round(float targetValue, int roundToDecimalPlaces ){
int valueInTwoDecimalPlaces = (int) (targetValue * Math.pow(10, roundToDecimalPlaces));
return (float) (valueInTwoDecimalPlaces / Math.pow(10, roundToDecimalPlaces));
}
}
Two possible situations :
Your company uses a proxy to connect to the public Maven repository. Then ask someone in your company what the IP address of the proxy is then put it in your settings.xml file
Your company has its/their own Maven repository/ies (Nexus repository for example). Then ask someone in your company what the Nexus repository is then put it in your pom.xml or in your settings.xml. See Adding maven nexus repo to my pom.xml and https://maven.apache.org/guides/mini/guide-multiple-repositories.html
Check out Reuxables although it comes at a cost.
I'm not sure about the circumstances where you need to convert an NSInteger
to an int
.
NSInteger is just a typedef:
NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
You can use NSInteger
any place you use an int
without converting it.
An update
Turns out now brew cask install sublime-text
installs the most up to date version (e.g. 3) by default and brew cask
is now part of the standard brew
-installation.
If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:
$('.hidden-element').get(0).height;
same for the width:
$('.hidden-element').get(0).width;
(thanks to Skeets O'Reilly for correction)
Get the precompiled binaries from http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/
Download pkg-config and its depend libraries :
FYI, you can kill the process in one command sudo fuser -k 3000/tcp
. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.
Try Build > Clean Solution, then Build > Build Solution. This works for me.
In addition to editing .bowerrc
to setup your default install path, you can also setup custom install paths for different file types.
There is a node package called bower-installer that provides a single command for managing alternate install paths.
run npm install -g bower-installer
Set up your bower.json
{
"name" : "test",
"version": "0.1",
"dependencies" : {
"jquery-ui" : "latest"
},
"install" : {
"path" : {
"css": "src/css",
"js": "src/js"
},
"sources" : {
"jquery-ui" : [
"components/jquery-ui/ui/jquery-ui.custom.js",
"components/jquery-ui/themes/start/jquery-ui.css"
]
}
}
}
Run the following command: bower-installer
This will install components/jquery-ui/themes/start/jquery-ui.css
to ./src/css
, etc
Here are some easy to folow steps and a great on hover tutorial its the examples that you can "play" with and test live.
http://fivera.net/simple-cool-live-examples-image-hover-css-effect/
Try Ctrl + K + D (don't lift the Ctrl key in between).
.html file
<ion-card-content>
<div class='summary_row'>
<div class='summarycell'>Header 1</div>
<div class='summarycell'>Header 2</div>
<div class='summarycell'>Header 3</div>
<div class='summarycell'>Header 4</div>
<div class='summarycell'>Header 5</div>
<div class='summarycell'>Header 6</div>
<div class='summarycell'>Header 7</div>
</div>
<div class='summary_row'>
<div class='summarycell'>
Cell1
</div>
<div class='summarycell'>
Cell2
</div>
<div class='summarycell'>
Cell3
</div>
<div class='summarycell'>
Cell5
</div>
<div class='summarycell'>
Cell6
</div>
<div class='summarycell'>
Cell7
</div>
<div class='summarycell'>
Cell8
</div>
</div>
.scss file
.row{_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
width: max-content;_x000D_
}_x000D_
.row:first-child .summarycell{_x000D_
font-weight: bold;_x000D_
text-align: center;_x000D_
}_x000D_
.cell{_x000D_
overflow: auto;_x000D_
word-wrap: break-word;_x000D_
width: 27vw;_x000D_
border: 1px solid #b3b3b3;_x000D_
padding: 10px;_x000D_
text-align: right;_x000D_
}_x000D_
.cell:nth-child(2){_x000D_
}_x000D_
.cell:first-child{_x000D_
width:41vw;_x000D_
text-align: left;_x000D_
}
_x000D_
If using @FeignClient, add e.g.
produces = "application/json"
to the @RequestMapping annotation
Unfortunately the size
attribute will not work very well. There will be extra space and too little space sometimes, depending on how the font is set up. (check out the example)
If you want this to work well, try watching for changes on the input, and resize it then. You probably want to set it to the input's scrollWidth
. We would need to account for box sizing, too.
In the following example, I'm setting the size
of the input to 1 to prevent it from having a scrollWidth
that is greater than our initial width (set manually with CSS).
// (no-jquery document.ready)_x000D_
function onReady(f) {_x000D_
"complete" === document.readyState_x000D_
? f() : setTimeout(onReady, 10, f);_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
[].forEach.call(_x000D_
document.querySelectorAll("input[type='text'].autoresize"),_x000D_
registerInput_x000D_
);_x000D_
});_x000D_
function registerInput(el) {_x000D_
el.size = 1;_x000D_
var style = el.currentStyle || window.getComputedStyle(el),_x000D_
borderBox = style.boxSizing === "border-box",_x000D_
boxSizing = borderBox_x000D_
? parseInt(style.borderRightWidth, 10) +_x000D_
parseInt(style.borderLeftWidth, 10)_x000D_
: 0;_x000D_
if ("onpropertychange" in el) {_x000D_
// IE_x000D_
el.onpropertychange = adjust;_x000D_
} else if ("oninput" in el) {_x000D_
el.oninput = adjust;_x000D_
}_x000D_
adjust();_x000D_
_x000D_
function adjust() {_x000D_
_x000D_
// reset to smaller size (for if text deleted) _x000D_
el.style.width = "";_x000D_
_x000D_
// getting the scrollWidth should trigger a reflow_x000D_
// and give you what the width would be in px if _x000D_
// original style, less any box-sizing_x000D_
var newWidth = el.scrollWidth + boxSizing;_x000D_
_x000D_
// so let's set this to the new width!_x000D_
el.style.width = newWidth + "px";_x000D_
}_x000D_
}
_x000D_
* {_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input.autoresize {_x000D_
width: 125px;_x000D_
min-width: 125px;_x000D_
max-width: 400px;_x000D_
}_x000D_
input[type='text'] {_x000D_
box-sizing: border-box;_x000D_
padding: 4px 8px;_x000D_
border-radius: 4px;_x000D_
border: 1px solid #ccc;_x000D_
margin-bottom: 10px;_x000D_
}
_x000D_
<label> _x000D_
Resizes:_x000D_
<input class="autoresize" placeholder="this will resize" type='text'>_x000D_
</label>_x000D_
<br/>_x000D_
<label>_x000D_
Doesn't resize:_x000D_
<input placeholder="this will not" type='text'>_x000D_
</label>_x000D_
<br/>_x000D_
<label>_x000D_
Has extra space to right:_x000D_
<input value="123456789" size="9" type="text"/>_x000D_
</label>
_x000D_
I think this should work in even IE6, but don't take my word for it.
Depending on your use case, you may need to bind the adjust function to other events. E.g. changing an input's value programmatically, or changing the element's style's display
property from none
(where scrollWidth === 0
) to block
or inline-block
, etc.
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...
here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
$('#select_id option:eq(0)').prop('selected', 'selected');
its good
I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${exec.main-class}</mainClass>
<systemProperties>
<systemProperty>
<key>myproperty</key>
<value>myvalue</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
var height = document.body.clientHeight;
var width = document.body.clientWidth;
Check: this article for better explanation.
First a CMP (comparison) instruction is called then one of the following:
jle - jump to line if less than or equal to
jge - jump to line if greater than or equal to
The lowest assembler works with is bytes, not bits (directly anyway). If you want to know about bit logic you'll need to take a look at circuit design.
Int32.parse(string)--->
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
result = Int32.Parse(s1); //1234
result = Int32.Parse(s2); //FormatException
result = Int32.Parse(s3); //ArgumentNullException
result = Int32.Parse(s4); //OverflowException
Convert.ToInt32(string) --> Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
For example:
result = Convert.ToInt32(s1); // 1234
result = Convert.ToInt32(s2); // FormatException
result = Convert.ToInt32(s3); // 0
result = Convert.ToInt32(s4); // OverflowException
?? Be careful!
This answer is based on undocumented APIs and recently (since iOS12) Apple is rejecting apps with this approach.
Original answer below
Swift 5
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
Swift 4
UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
NOTE: The following method works for all the versions below iOS 11, for higher versions the app might get rejected since it's a private API
Sometimes we want to take a user to settings other than our app settings. The following method will help you achieve that:
First, configure the URL Schemes in your project. You will find it in Target -> Info -> URL Scheme. click on + button and type prefs in URL Schemes
Swift 5
UIApplication.shared.open(URL(string: "App-prefs:Bluetooth")!)
Swift 3
UIApplication.shared.open(URL(string:"App-Prefs:root=General")!, options: [:], completionHandler: nil)
Swift
UIApplication.sharedApplication().openURL(NSURL(string:"prefs:root=General")!)
Objective-C
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];
and following are all the available URLs
**On IOS < 12 **
On IOS 13
App-prefs:DO_NOT_DISTURB
Not tested
App-prefs:TWITTER (??)
Note: Network setting will not be opened in a simulator, but the link will work on a real device.
For anyone needing just top or left position, slight modifications to @Nickf's readable code does the trick.
function getTopPos(el) {
for (var topPos = 0;
el != null;
topPos += el.offsetTop, el = el.offsetParent);
return topPos;
}
and
function getLeftPos(el) {
for (var leftPos = 0;
el != null;
leftPos += el.offsetLeft, el = el.offsetParent);
return leftPos;
}
Add the css styling text-align: center
to the control.
Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:
<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>
You can make it so:
type MessageType int32
const (
TEXT MessageType = 0
BINARY MessageType = 1
)
With this code compiler should check type of enum
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces
This will add the number of spaces needed, provided the field has length >= the length of the name provided
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
Well, I know the reason, but I can't show it:
For files that contain only PHP code, the closing tag (
?>
) is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.
Source: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html
If you want to kill the process that's listening on port 8080, you could use PowerShell. Just combine Get-NetTCPConnection
cmdlet with Stop-Process
.
Tested and should work with PowerShell 5 on Windows 10 or Windows Server 2016. However, I guess that it should also work on older Windows versions that have PowerShell 5 installed.
Here is an example:
PS C:\> Stop-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess
Confirm
Are you sure you want to perform the Stop-Process operation on the following item: MyTestServer(9408)?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
I ran into the same issue and found another way to do this. It worked for in my case as it was a relatively small application.
First, the user will a click button in the component which needs to be printed. This will set a flag that can be accessed by the app component. Like so
.html file
<button mat-button (click)="printMode()">Print Preview</button>
.ts file
printMode() {
this.utilities.printMode = true;
}
In the html of the app component, we hide everything except the router-outlet. Something like below
<div class="container">
<app-header *ngIf="!utilities.printMode"></app-header>
<mat-sidenav-container>
<mat-sidenav *ngIf="=!utilities.printMode">
<app-sidebar></app-sidebar>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
</div>
With similar ngIf conidtions, we can also adjust the html template of the component to only show or hide things in printMode. So that the user will see only what needs to get printed when print preview is clicked.
We can now simply print or go back to normal mode with the below code
.html file
<button mat-button class="doNotPrint" (click)="print()">Print</button>
<button mat-button class="doNotPrint" (click)="endPrint()">Close</button>
.ts file
print() {
window.print();
}
endPrint() {
this.utilities.printMode = false;
}
.css file (so that the print and close button's don't get printed)
@media print{
.doNotPrint{display:none !important;}
}
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvmÂÂ.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
Try System.Func<T>
and System.Action
you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java
You can simply use the data-interval
attribute of the carousel
class.
It's default value is set to data-interval="3000"
i.e 3seconds.
All you need to do is set it to your desired requirements.
just add below line and access direct xml object
import kotlinx.android.synthetic.main.activity_main.*
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txt_HelloWorld.text = "abc"
}
replace activity_main according to your XML name
The dll is missing in the published (deployed environment). That is the reason why it is working in the local i.e. Visual Studio but not in the Azure Website Environment.
Just do Copy Local = true in the properties for the assembly(System.Web.Http.WebHost) and then do a redeploy, it should work fine.
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
Link to the documentation for the ComboBox DropDownStyle property on MSDN.
You can easily change the mysql password if deployed on xampp through provided phpadmin gui.
phpMyAdmin -> User Accounts -> Edit Privileges (Select the intended user) -> Change Password (Tab)
Here is a standard lib (http
) async / await solution.
const http = require("http");
const fetch = async (url) => {
return new Promise((resolve, reject) => {
http
.get(url, (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", () => {
resolve(data);
});
})
.on("error", (err) => {
reject(err);
});
});
};
Usage:
await fetch("http://example.com");
Add this this to dependencies to force using latest version of findbugs library:
compile 'com.google.code.findbugs:jsr305:2.0.1'
Dave Delongs's Swift 2.0 answer was crashing for me (in iOS 9)
But this worked:
let fetchRequest = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try managedObjectContext.executeRequest(deleteRequest)
try managedObjectContext.save()
}
catch let error as NSError {
// Handle error
}
import time
from datetime import datetime
t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())
result: 3.0
layoutParams2.gravity = Gravity.RIGHT|Gravity.BOTTOM;
use this to add mor than one gravity
Another way is to use System.Threading.ManualResetEvent
dim SecondsToWait as integer = 5
Dim Waiter As New ManualResetEvent(False)
Waiter.WaitOne(SecondsToWait * 1000) 'to get it into milliseconds
Here is a special case if you want the first entry (or close to it) in an OrderedDict, without creating a list. (This has been updated to Python 3):
>>> from collections import OrderedDict
>>>
>>> d = OrderedDict()
>>> d["foo"] = "one"
>>> d["bar"] = "two"
>>> d["baz"] = "three"
>>> next(iter(d.items()))
('foo', 'one')
>>> next(iter(d.values()))
'one'
(The first time you say "next()", it really means "first.")
In my informal test, next(iter(d.items()))
with a small OrderedDict is only a tiny bit faster than items()[0]
. With an OrderedDict of 10,000 entries, next(iter(d.items()))
was about 200 times faster than items()[0]
.
BUT if you save the items() list once and then use the list a lot, that could be faster. Or if you repeatedly { create an items() iterator and step through it to to the position you want }, that could be slower.
This command might come in handy. This will not record the command that is executed
history -d $((HISTCMD-1)) && <Your Command Here>
I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.
You have it like this:
<Metrics>
<Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>
If it were like this instead:
<Metrics>
<Metric>
<id>TransactionCleanupThread.RefundOldTrans</id>
<type>timer</type>
.
.
.
Then you could simply use this SQL statement.
SELECT
Sqm.SqmId,
Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm
To me this is much less confusing than using the outer apply or cross apply.
I hope this helps someone else looking for a simpler solution!
For databases:
Just use these commands:
USE db_name;
SELECT @@character_set_database;
-- or:
-- SELECT @@collation_database;
You can do this:
DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5
SELECT CAST(((@maxval + 1) - @minval) *
RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)
And that was taken directly from this link, I don't really know how to give proper credit for this answer.
fixed positioning alone should have fixed that problem but another good workaround to avoid this issue is to place your modal divs or elements at the bottom of the page not within your sites layout. Most modal plugins give their modal positioning absolute to allow the user keep main page scrolling.
<html>
<body>
<!-- Put all your page layouts and elements
<!-- Let the last element be the modal elemment -->
<div id="myModals">
...
</div>
</body>
</html>
To remove the upstream for the current branch do:
$ git branch --unset-upstream
This is available for Git v.1.8.0 or newer. (Sources: 1.7.9 ref, 1.8.0 ref)
The directory or one of the parent directories must be marked as Source Root
(In this case, it appears in blue).
If this is not the case, right click your root source directory -> Mark As -> Source Root.
I was also having the same problem, but I set the height value in my CSS to auto and that fixed my problem. Also, don't forget to do the display property.
#image {
height: auto;
width: auto;
max-height: 550px;
max-width: 1200px;
margin-left: auto;
margin-right: auto;
display: block;
}
Just run this in a console.
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell
It installs the latest version using a Chocolatey repository.
Originally I was using command cinst powershell 3.0.20121027
, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell
refers to version 3.0 of PowerShell, and that may change in future.
See the Chocolatey PowerShell package page for details on what version will be installed.
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
You could just use list comprehension:
property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good]
or
property_asel = [property_a[i] for i in good_indices]
The latter one is faster because there are fewer good_indices
than the length of property_a
, assuming good_indices
are precomputed instead of generated on-the-fly.
Edit: The first option is equivalent to itertools.compress
available since Python 2.7/3.1. See @Gary Kerr's answer.
property_asel = list(itertools.compress(property_a, good_objects))
If you're in pug:
html
head
title Pug
body
a(href="http://www.example.com" target="_blank") Example
button(onclick="window.open('http://www.example.com')") Example
And if you're puggin' Semantic UI:
html
head
title Pug
link(rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css')
body
.ui.center.aligned.container
a(href="http://www.example.com" target="_blank") Example
.ui.center.aligned.container
.ui.large.grey.button(onclick="window.open('http://www.example.com')") Example
You may be looking for the ProtectedData
class, which encrypts data using the user's logon credentials.
It sounds like you're using an incorrect address:
To access the Service I enter http://localhost/project/myService.svc/FileUpload
Assuming you mean this is the address you give your client code then I suspect it should actually be:
http://localhost/project/myService.svc
I use this syntax for flexibility and speed -
begin
--
with KLUJ as
( select 0 ROES from dual
union
select count(*) from MY_TABLE where rownum = 1
) select max(ROES) into has_rows from KLUJ;
--
end;
Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.
I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.
Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:
I have a table with 50000 elements, the result i was looking for was 739 elements.
My query at first was this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
SELECT MAX(p2.anno)
FROM prodotto p2
WHERE p2.fixedId = p.fixedId
)
and it took 7.9s to execute.
My query at last is this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
SELECT p2.fixedId, MAX(p2.anno)
FROM prodotto p2
WHERE p.azienda_id = p2.azienda_id
GROUP BY p2.fixedId
)
and it took 0.0256s
Good SQL, good.
Jason's Shavers series of articles here http://jasonrshaver.com/?tag=/Client+Certificates explain exactly how to set up your applicationhost.config site entry to allow the app to run in either ssl or standard http.
One of the things he recommends is putting two binding entries for the site. This is what I did.
<bindings>
<binding protocol="http" bindingInformation="*:59945:localhost" />
<binding protocol="https" bindingInformation="*:44300:localhost"/>
</bindings>
He also recommends changing other settings as well. It worked on two of my three machines. Each time I am told to manually configure a site in the application host it usually has to do with the bindings. (example using same port for multiple web apps.)
You can do it by putting your images on a fixed path (for example: /var/images, or c:\images), add a setting in your application settings (represented in my example by the Settings.class), and load them like that, in a HttpServlet
of yours:
String filename = Settings.getValue("images.path") + request.getParameter("imageName")
FileInputStream fis = new FileInputStream(filename);
int b = 0;
while ((b = fis.read()) != -1) {
response.getOutputStream().write(b);
}
Or if you want to manipulate the image:
String filename = Settings.getValue("images.path") + request.getParameter("imageName")
File imageFile = new File(filename);
BufferedImage image = ImageIO.read(imageFile);
ImageIO.write(image, "image/png", response.getOutputStream());
then the html code would be <img src="imageServlet?imageName=myimage.png" />
Of course you should think of serving different content types - "image/jpeg", for example based on the file extension. Also you should provide some caching.
In addition you could use this servlet for quality rescaling of your images, by providing width and height parameters as arguments, and using image.getScaledInstance(w, h, Image.SCALE_SMOOTH
), considering performance, of course.
While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE
Let check the parameter value.
If in Case it is :
SQL> show parameter resource_limit
NAME TYPE VALUE
------------------------------------ ----------- ---------
resource_limit boolean FALSE
Its mean resource limit is off,we ist have to enable it.
Use the ALTER SYSTEM statement to turn on resource limits.
SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.
For classed based views use self.request.user.id
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
"Topology was destroyed" might be caused by mongoose disconnecting before mongo document indexes are created, per this comment
In order to make sure all models have their indexes built before disconnecting, you can:
await Promise.all(mongoose.modelNames().map(model => mongoose.model(model).ensureIndexes()));
await mongoose.disconnect();
I tried all the solutions but it still wasn't sufficient. After some more digging I eventually found I had also to set the 'file_priv' flag, and restart mysql.
To resume :
Grant the privileges :
> GRANT ALL PRIVILEGES
ON my_database.*
to 'my_user'@'localhost';
> GRANT FILE ON *.* TO my_user;
> FLUSH PRIVILEGES;
Set the flag :
> UPDATE mysql.user SET File_priv = 'Y' WHERE user='my_user' AND host='localhost';
Finally restart the mysql server:
$ sudo service mysql restart
After that, I could write into the secure_file_priv
directory. For me it was /var/lib/mysql-files/, but you can check it with the following command :
> SHOW VARIABLES LIKE "secure_file_priv";
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'organizer'@'localhost' WITH GRANT OPTION;
CREATE USER 'username'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'organizer'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
no need to stop/start mysql
A function is, at a basic level, a block of code that can executed, not when written, but when called. So let's say I have the following piece of code, which is a simple multiplication function:
def multiply(x,y):
return x * y
So if I called the function with multiply(2,3)
, it would return the value 6. If I modified the function so it looks like this:
def multiply(x,y):
print(x*y)
return x*y
...then the output is as you would expect, the number 6 printed. However, the difference between these two statements is that print
merely shows something on the console, but return
"gives something back" to whatever called it, which is often a variable. The variable is then assigned the value of the return statement in the function that it called. Here is an example in the python shell:
>>> def multiply(x,y):
return x*y
>>> multiply(2,3) #no variable assignment
6
>>> answer = multiply(2,3) #answer = whatever the function returns
>>> answer
6
So now the function has returned the result of calling the function to the place where it was called from, which is a variable called 'answer' in this case.
This does much more than simply printing the result, because you can then access it again. Here is an example of the function using return statements:
>>> x = int(input("Enter a number: "))
Enter a number: 5
>>> y = int(input("Enter another number: "))
Enter another number: 6
>>> answer = multiply(x,y)
>>> print("Your answer is {}".format(answer)
Your answer is 30
So it basically stores the result of calling a function in a variable.
Reading the friendly manual? Who'd want to do that?
start = Time.now
largest_known_fixnum = 1
smallest_known_bignum = nil
until smallest_known_bignum == largest_known_fixnum + 1
if smallest_known_bignum.nil?
next_number_to_try = largest_known_fixnum * 1000
else
next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky
end
if next_number_to_try <= largest_known_fixnum ||
smallest_known_bignum && next_number_to_try >= smallest_known_bignum
raise "Can't happen case"
end
case next_number_to_try
when Bignum then smallest_known_bignum = next_number_to_try
when Fixnum then largest_known_fixnum = next_number_to_try
else raise "Can't happen case"
end
end
finish = Time.now
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"
In Kotlin
fun hideKeyboard(activity: BaseActivity) {
val view = activity.currentFocus?: View(activity)
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
For Mac you can do : View > Command Palette > Shell command > "install code command in path". I'd assume there would be something similar for other OS's. After I do
which code
and it tells me it put it in /usr/local/bin
Try this one as it worked for me:
SSIS - the value cannot be converted because of a potential loss of data
super
is used to access methods of the base class while this
is used to access methods of the current class.
Extending the notion, if you write super()
, it refers to constructor of the base class, and if you write this()
, it refers to the constructor of the very class where you are writing this code.
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
I presume you want to copy C:\OtherFolder\fileToCheck.bat to C:\MyFolder if the existing file in C:\MyFolder is either missing entirely, or if it is missing "stringToCheck".
FINDSTR sets ERRORLEVEL to 0 if the string is found, to 1 if it is not. It also sets errorlevel to 1 if the file is missing. It also prints out each line that matches. Since you are trying to use it as a condition, I presume you don't need or want to see any of the output. The 1st thing I would suggest is to redirect both the normal and error output to nul using >nul 2>&1
.
Solution 1 (mostly the same as previous answers)
You can use IF ERRORRLEVEL N
to check if the errorlevel is >= N. Or you can use IF NOT ERRORLEVEL N
to check if errorlevel is < N. In your case you want the former.
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if errorlevel 1 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
Solution 2
You can test for a specific value of errorlevel by using %ERRORLEVEL%. You can probably check if the value is equal to 1, but it might be safer to check if the value is not equal to 0, since it is only set to 0 if the file exists and it contains the string.
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if not %errorlevel% == 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
or
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if %errorlevel% neq 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
Solution 3
There is a very compact syntax to conditionally execute a command based on the success or failure of the previous command: cmd1 && cmd2 || cmd3
which means execute cmd2 if cmd1 was successful (errorlevel=0), else execute cmd3 if cmd1 failed (errorlevel<>0). You can use && alone, or || alone. All the commands need to be on the same line. If you need to conditionally execute multiple commands you can use multiple lines by adding parentheses
cmd1 && (
cmd2
cmd3
) || (
cmd4
cmd5
)
So for your case, all you need is
findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"
But beware - the ||
will respond to the return code of the last command executed. In my earlier pseudo code the ||
will obviously fire if cmd1 fails, but it will also fire if cmd1 succeeds but then cmd3 fails.
So if your success block ends with a command that may fail, then you should append a harmless command that is guaranteed to succeed. I like to use (CALL )
, which is harmless, and always succeeds. It also is handy that it sets the ERRORLEVEL to 0. There is a corollary (CALL)
that always fails and sets ERRORLEVEL to 1.
The fastest way it is to use the Oracle collect function.
You can also do this:
select *
2 from (
3 select deptno,
4 case when row_number() over (partition by deptno order by ename)=1
5 then stragg(ename) over
6 (partition by deptno
7 order by ename
8 rows between unbounded preceding
9 and unbounded following)
10 end enames
11 from emp
12 )
13 where enames is not null
Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.
I was catching GuzzleHttp\Exception\BadResponseException
as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException
when DNS for domain wasn't available.
So my suggestion is - catch GuzzleHttp\Exception\ConnectException
to be safe about DNS errors as well.
You can also use df.icol(n)
to access a column by integer.
Update: icol
is deprecated and the same functionality can be achieved by:
df.iloc[:, n] # to access the column at the nth position
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
A faster way is to use javascript directly, eg.
var parent = $(innerdiv.get(0).parentNode.parentNode.parentNode);
This runs significantly faster on my browser than chaining jQuery .parent()
calls.
Ensure these two and it should work:-
Fixes this issue on windows like a charm.
This solution works like a charm (updated in 2017 to honor that log_format needs to be in the http part of the nginx config):
log_format postdata $request_body;
server {
# (...)
location = /post.php {
access_log /var/log/nginx/postdata.log postdata;
fastcgi_pass php_cgi;
}
}
I think the trick is making nginx believe that you will call a cgi script.
This worked for me :
select option {
color: black;
}
select:not(:checked) {
color: gray;
}
You can use pseudo element to get the effect you want like I did in that Fiddle.
CSS:
.title a {
display: block;
width: 340px;
height: 338px;
color: black;
position: relative;
}
.title a:after {
background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
content: "";
opacity: 0;
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0;
/* TRANSISITION */
transition: opacity 1s ease-in-out;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{
opacity: 1;
}
HTML:
<div class="title">
<a href="#">HYPERLINK</a>
</div>
In short: Replace badge-important
with either alert-danger
or progress-bar-danger
.
It looks like this: Bootply Demo.
You might combine the CSS class badge
with alert-*
or progess-bar-*
to color them:
With class="badges alert-*"
<span class="badge alert-info">badge</span> Info
<span class="badge alert-success">badge</span> Success
<span class="badge alert-danger">badge</span> Danger
<span class="badge alert-warning">badge</span> Warning
Alerts Docu: http://getbootstrap.com/components/#alerts
With class="badges progress-bar-*"
(as suggested by @clami219)
<span class="badge progress-bar-info">badge</span> Info
<span class="badge progress-bar-success">badge</span> Success
<span class="badge progress-bar-danger">badge</span> Danger
<span class="badge progress-bar-warning">badge</span> Warning
Progress-Bar Docu: http://getbootstrap.com/components/#progress-alternatives
Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
... and is used like this...
load_json("test2.html.js")
...and this is the <head>
...
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
You cannot disable linker warning 4099, as said @John Weldon.
You should rebuild library with some project configuration changes. You have several options:
In case you want to see what this all means, here is a blow-by-blow of everything:
CREATE TABLE `users_partners` (
`uid` int(11) NOT NULL DEFAULT '0',
`pid` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`uid`,`pid`),
KEY `partner_user` (`pid`,`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
Primary key is based on both columns of this quick reference table. A Primary key requires unique values.
Let's begin:
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...1 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1);
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1);
...0 row(s) affected
INSERT INTO users_partners (uid,pid) VALUES (1,1) ON DUPLICATE KEY UPDATE uid=uid
...0 row(s) affected
note, the above saved too much extra work by setting the column equal to itself, no update actually needed
REPLACE INTO users_partners (uid,pid) VALUES (1,1)
...2 row(s) affected
and now some multiple row tests:
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'
INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...3 row(s) affected
no other messages were generated in console, and it now has those 4 values in the table data. I deleted everything except (1,1) so I could test from the same playing field
INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4) ON DUPLICATE KEY UPDATE uid=uid
...3 row(s) affected
REPLACE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...5 row(s) affected
So there you have it. Since this was all performed on a fresh table with nearly no data and not in production, the times for execution were microscopic and irrelevant. Anyone with real-world data would be more than welcome to contribute it.
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
If you want to do it in multiple, easy-to-remember commands:
docker ps -a
docker start -i <name/id>
The -i
flag tells docker to attach to the container's stdin.
If the container wasn't started with an interactive shell to connect to, you need to do this to run a shell:
docker start <name/id>
docker exec -it <name/id> /bin/sh
The /bin/sh
is the shell usually available with alpine-based images.
This will maybe give you a hint on what went wrong.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal bdTest = new BigDecimal(0.745);
BigDecimal bdTest1 = new BigDecimal("0.745");
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
}
}
The problem is, that your input (a double x=0.745;
) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals
, this is already below 0.745, so it rounds down...
Try not to use the BigDecimal(double/float)
constructors.
I got this error briefly after renaming the App_Code folder. Actually, I accidentally dragged the whole folder to the App_data folder. VS 2015 didn't complain it was difficult to spot what had gone wrong.
Here's how to setup a scrollview using Xcode 11
1 - Add scrollview and set top,bottom,leading and trailing constraints
2 - Add a Content View to the scrollview, drag a connection to the Content Layout Guide and select Leading, Top, Bottom and Trailing. Make sure to set its' values to 0 or the constants you want.
3 - Drag from the Content View to the Frame Layout Guide and select Equal Widths
4 - Set a height constraint constant to the Content View
Interesting question.
If you can't find a better method, you can always replace.
In case you're opting for it, you could use this C# Escape Sequence List:
This list can be found in the C# Frequently Asked Questions What character escape sequences are available?
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
import java.util.Scanner;
public class LargestSmallestNumbers {
private static Scanner input;
public static void main(String[] args) {
int count,items;
int newnum =0 ;
int highest=0;
int lowest =0;
input = new Scanner(System.in);
System.out.println("How many numbers you want to enter?");
items = input.nextInt();
System.out.println("Enter "+items+" numbers: ");
for (count=0; count<items; count++){
newnum = input.nextInt();
if (highest<newnum)
highest=newnum;
if (lowest==0)
lowest=newnum;
else if (newnum<=lowest)
lowest=newnum;
}
System.out.println("The highest number is "+highest);
System.out.println("The lowest number is "+lowest);
}
}
ResourceBundle doesn't load files? You need to get the files into a resource first. How about just loading into a FileInputStream then a PropertyResourceBundle
FileInputStream fis = new FileInputStream("skyscrapper.properties");
resourceBundle = new PropertyResourceBundle(fis);
Or if you need the locale specific code, something like this should work
File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);
You can access afterRender
hook by using plugins
.
And here are all the plugin api available.
In html file:
<html>
<canvas id="myChart"></canvas>
<div id="imgWrap"></div>
</html>
In js file:
var chart = new Chart(ctx, {
...,
plugins: [{
afterRender: function () {
// Do anything you want
renderIntoImage()
},
}],
...,
});
const renderIntoImage = () => {
const canvas = document.getElementById('myChart')
const imgWrap = document.getElementById('imgWrap')
var img = new Image();
img.src = canvas.toDataURL()
imgWrap.appendChild(img)
canvas.style.display = 'none'
}
Here's my quick and simple function for getting the absolute path from a relative path.
The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.
Example:
Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")
Code:
' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
Dim absPath As String
Dim pos As Integer
absPath = ActiveWorkbook.Path
' Make sure paths are in correct format
relativePath = Replace(relativePath, "/", "\")
absPath = Replace(absPath, "/", "\")
Do While Left$(relativePath, 3) = "..\"
' Remove level from relative path
relativePath = Mid$(relativePath, 4)
' Remove level from absolute path
pos = InStrRev(absPath, "\")
absPath = Left$(absPath, pos - 1)
Loop
GetAbsolutePath = PathCombine(absPath, relativePath)
End Function
I've read so many threads and try so many pieces of code. After gathering all that stuff, the only way I found to cleanly empty the login and password fields and reset their background to white was the following :
$(window).load(function() {
setTimeout(function() {
$('input:-webkit-autofill')
.val('')
.css('-webkit-box-shadow', '0 0 0px 1000px white inset')
.attr('readonly', true)
.removeAttr('readonly')
;
}, 50);
});
Feel free to comment, I'm opened to all enhancements if you find some.
You can use a Multiset (from guava). It will give you the count for each object. For example:
Multiset<Character> chars = HashMultiset.create();
for (int i = 0; i < string.length(); i++) {
chars.add(string.charAt(i));
}
Then for each character you can call chars.count('a')
and it returns the number of occurrences
Please also note that from iOS9 we can define constraints programmatically "more concise, and easier to read" using subclasses of the new helper class NSLayoutAnchor.
An example from the doc:
[self.cancelButton.leadingAnchor constraintEqualToAnchor:self.saveButton.trailingAnchor constant: 8.0].active = true;
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
With lodash:
_.each([1, 2, 3], (item) => {
doSomeThing(item);
});
//Or:
_.each([1, 2, 3], doSomeThing);
Or if you want to do something N times:
const N = 10;
_.times(N, () => {
doSomeThing();
});
//Or shorter:
_.times(N, doSomeThing);
Refer to this link for lodash
installation
http://jqapi.com/ Traversing--> Tree Traversal --> Children
You have to add a manifest permission entry:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(of course you should list all other permissions that your app uses).
Then, implement BroadcastReceiver class, it should be simple and fast executable. The best approach is to set an alarm in this receiver to wake up your service (if it's not necessary to keep it running ale the time as Prahast wrote).
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyService.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pi);
}
}
Then, add a Receiver class to your manifest file:
<receiver android:enabled="true" android:name=".receivers.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Calling str(...)
is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,
:
print(','.join(str(x) for x in list_of_ints))
Updated June 24, 2020
You need to update to the latest gradle
version to solve this issue.
Please make sure you are on the latest Android Studio
and then update your project level build.gradle
by updating this dependency
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.0'
}
}
It might show a popup asking your permission to update gradle
, please update and it will download the latest distribution automatically and the issue will be resolved.
Or else you can
Get Latest Gradle 5.6.4 from here and Add it manually
If you don't want to download it manually:
Open YourProject > gradle > wrapper > gradle-wrapper.properties
and replace
distributionUrl=https\://services.gradle.org/distributions/gradle-version-number-all.zip
With
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
Rebuild the project or just run gradle sync again.
If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.
And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height. Below code works for me.
LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);
LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);
parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
Taken from the MySQL 8.0 Reference Manual:
utf8mb4
: A UTF-8 encoding of the Unicode character set using one to four bytes per character.
utf8mb3
: A UTF-8 encoding of the Unicode character set using one to three bytes per character.
In MySQL utf8
is currently an alias for utf8mb3
which is deprecated and will be removed in a future MySQL release. At that point utf8
will become a reference to utf8mb4
.
So regardless of this alias, you can consciously set yourself an utf8mb4
encoding.
To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):
To avoid ambiguity about the meaning of
utf8
, consider specifyingutf8mb4
explicitly for character set references instead ofutf8
.
You can simply use pkill -f
like this:
pkill -f 'java -jar'
EDIT: To kill a particular java process running your specific jar use this regex based pkill command:
pkill -f 'java.*lnwskInterface'
As a complement to other answers note that you can also put the lang
attribute on various HTML tags inside a page.
For example to give a hint to the spellchecker that the input text should be in english:
<input ... spellcheck="true" lang="en"> ...
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
this is my proposition i think its easier with sets than with a for loop
def unique_common_items(list1, list2):
# Produce the set of *unique* common items in two lists.
return list(set(list1) & set(list2))
All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C.
They are called the argument-unpacking and keyword-argument-unpacking operators.
You can try this simple android dialog popup library to cut the cluttered dialog code. It is very simple to use on your activity. after that you can have this code in your activity to show dialog
Pop.on(this).with().title(R.string.title).layout(R.layout.custom_pop).show();
where R.layout.custom_pop is your custom layout the way you want to decorate your dialog.
Using the "Find in Files" function of Notepad++ worked fine for me (ctrl + H, Find in Files).
Get ahold of BeanUtils from Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/
Probably the Apache variation (commons beans) has similar functionality.
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.
You need to do custom SQL as exemplified in this snippet:
Or in a custom manager as shown in the online Django docs:
What do you get from running which port
as your regular user account? Try it from a freshly opened terminal. Try again after renaming .bash_profile
to .profile
. Can you run port
as a regular user, even with no arguments?
select ID from A where ID not in (select ID from B);
or
select ID from A except select ID from B;
Your second question:
delete from A where ID not in (select ID from B);
Its blank because you are writing to file
. you should write to output
using php://output
instead and also send header information to indicate that it's csv.
Example
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
You can also use %
as follows:
source = "#{ROOT_DIR}/%s/App.config" % project
This approach works with '
(single) quotation mark as well.
You could do a
mysqlimport --columns='head -n 1 $yourfile' --ignore-lines=1 dbname $yourfile`
That is, if your file is comma separated and is not semi-colon separated. Else you might need to sed
through it too.
I recently encountered the same issue however I am using Windows 10 Technical Preview Build 10041 and SQL Server 2014 (Advanced).
Follow the same advice from above:
In particular, my problem was that I did not enable the TCP/IP in Sql Server Configuration Manager->SQL Server Network Configuration->Protocols for SQLEXPRESS.
Once you open it, you have to go to the IP Addresses tab and for me, changing IPAll to TCP port 1433 and deleting the TCP Dynamic Ports value worked.
Follow the other steps to make sure 1433 is listening (Use netstat -an to make sure 0.0.0.0:1433 is LISTENING.), and that you can telnet to the port from the client machine.
Finally, I second the suggestion to remove the \SQLEXPRESS from the connection.
AND ----> That last line is important! It looks like to be Windows 10 specific; remove \SQLEXPRESS from your connection string. What was frusting was that SQL Management Studio connects just fine using either connection string (full or short), however Visual Studio only accepted the connection string without the \SQLEXPRESS.
I believe right now your output printing as below
~ echo -e "String1\nString2"
String1
String2
You can use xargs
to get multiline stdout into same line.
~ echo -e "String1\nString2" | xargs
String1 String2
~
You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:
method:POST
Screenshot
Tested with Chrome Version 53.
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
This can be done by using PsExec
which can be downloaded here
psexec \\computer_name -u username -p password ipconfig
If this isn't working try doing this :-
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.
Add a new DWORD value called LocalAccountTokenFilterPolicy
$_SERVER['REQUEST_URI']
For more details on what info is available in the $_SERVER array, see the PHP manual page for it.
If you also need the query string (the bit after the ?
in a URL), that part is in this variable:
$_SERVER['QUERY_STRING']
Yes, below is a link of docs.Oracle where you can find complete list of escape characters in Java.
Escape characters are always preceded with "\" and used to perform some specific task like go to next line etc.
For more Details on Escape Character Refer following link:
https://docs.oracle.com/javase/tutorial/java/data/characters.html
I think the accepted answer is great, but why don't you do it explicitly? I feel more people would understand your code, and that is in agreement with PEP 8:
max_value = max(my_list)
max_index = my_list.index(max_value)
This method is also about three times faster than the accepted answer:
import random
from datetime import datetime
import operator
def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val
def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val
if __name__ == "__main__":
from timeit import Timer
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(100)]")
print "Explicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(100)]")
print "Implicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
Results as they run in my computer:
Explicit: 8.07 usec/pass
Implicit: 22.86 usec/pass
Other set:
Explicit: 6.80 usec/pass
Implicit: 19.01 usec/pass
Your import has a subtle error:
import java.awt.List;
It should be:
import java.util.List;
The problem is that both awt
and Java's util package provide a class called List
. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList
extends java.util.List
, not java.awt.List
so if it wasn't for the generics, it would have still been a problem.
Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.
import org.omg.DynamicAny.NameValuePair;
should be
import org.apache.http.NameValuePair
nameValuePairs
now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity
, which is List<? extends NameValuePair>
, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair
did not extend org.apache.http.NameValuePair
and the shortened type name NameValuePair
evaluated to org.omg...
in your file, but org.apache...
in their code.
class Foo: is called old style class and class X(object): is called new style class.
Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"
Use this:
$('a[href^="#"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
}
});
I faced this while git pull. For mine edited the global git config file that fixed problem.
Goto your home folder and open .gitconfig file. Usually C:\Users\.gitconfig
If the file is not there create it
[http]
sslcainfo = E:\systools\git-1.8.5.2\bin\curl-ca-bundle.crt
There you have to given your own git installation path. I have used portable version of git here.
Then git clone / pull it will work.
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference doc gives you the entire list of options you can use with .find
, including how to limit by number, id, or any other arbitrary column/constraint.
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
You can also swap the order of these chained calls, doing .select(...).where(...).first
- all these calls do is construct the SQL query and then send it off.
Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
git difftool tag/branch filename
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (textField.getText().length()>0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Massage",
JOptionPane.ERROR_MESSAGE);
}
}
});
on linux pip install library_that_you_need Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project
I had a similar issue/error..
fixed it by moving
apply plugin: 'com.google.gms.google-services'
to the end of app level gradle file.
And updated the version of gms:play-services
and gms:play-services auth
<?php
pclose(popen("start /B test.bat", "r")); die();
?>
My experience with this was that when I had this in every execution it was fine using the provider as a string like this
Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");
But when I optimized and put the following in the constructor:
if(bounctCastleProvider == null) {
bounctCastleProvider = new BouncyCastleProvider();
}
if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
Security.addProvider(bouncyCastleProvider);
}
Then I had to use provider like this or I would get the above error:
new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);
I am using bcpkix-jdk15on version 1.65
we had: SQLSTATE[HY000]: General error: 1114 The table 'catalog_product_index_price_bundle_sel_tmp' is full
solved by:
edit config of db:
nano /etc/my.cnf
tmp_table_size=256M max_heap_table_size=256M
Pretty simple method is to just pass the creds in the url, can be slightly suspect though - use with caution.
import os
def getRepo(repo_url, login_object):
'''
Clones the passed repo to my staging dir
'''
path_append = r"stage\repo" # Can set this as an arg
os.chdir(path_append)
repo_moddedURL = 'https://' + login_object['username'] + ':' + login_object['password'] + '@github.com/UserName/RepoName.git'
os.system('git clone '+ repo_moddedURL)
print('Cloned!')
if __name__ == '__main__':
getRepo('https://github.com/UserName/RepoYouWant.git', {'username': 'userName', 'password': 'passWord'})
I don't think one needs it any more. The latest versions of Eclipse have Maven plugin enabled. So you will just need to import a Maven project into Eclipse and no more as an existing project. Eclipse will create the needed .project, .settings, .classpath files based on your pom.xml and environment settings (installed Java version, etc.) . The earlier versions of Eclipse needed to have run the command mvn eclipse:eclipse
which produced the same result.
http://www.scribd.com/doc/2546837/New-Subquery-Optimizations-In-MySQL-6
Please add the correct mime-types to your code - at least these ones:
.jpeg -> image/jpeg
.gif -> image/gif
.png -> image/png
A list of mime-types can be found here.
Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:
$allowedExts = array(
"pdf",
"doc",
"docx"
);
$allowedMimeTypes = array(
'application/msword',
'text/pdf',
'image/gif',
'image/jpeg',
'image/png'
);
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( 20000 < $_FILES["file"]["size"] ) {
die( 'Please provide a smaller file [E/1].' );
}
if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide another file type [E/2].');
}
if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) )
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
die('Please provide another file type [E/3].');
}
You may use the following code to remove non-English letters:
import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
This will return
123456790 ABC#%? .()
Make sure you correctly define the project's JDK and restart IntelliJ (full restart).
You're using share folders, so you need to install VirtualBox Guest Additions inside your virtual machine to support that feature.
If you're using Vagrant (OS X: brew cask install vagrant
), run:
vagrant plugin install vagrant-vbguest
vagrant vbguest
In case it fails, check the logs, e.g.
vagrant ssh -c "cat /var/log/vboxadd-install.log"
Maybe you're just missing the kernel header files.
Inside VM, you should install Guest Additions, kernel headers and start the service and double check if kernel extension is running.
This depends on the guest operating system, so here are brief steps:
Install kernel include headers (required by VBoxLinuxAdditions).
sudo apt-get update && sudo apt-get install kernel-devel
sudo yum update && sudo yum -y install kernel-headers kernel-devel
Install Guest Additions (this depends on the operating system).
Ubuntu: sudo apt-get -y install dkms build-essential linux-headers-$(uname -r) virtualbox-guest-additions-iso
If you can't find it, check by aptitude search virtualbox
.
Debian: sudo apt-get -y install build-essential module-assistant virtualbox-ose-guest-utils
If you can't find it, check by dpkg -l | grep virtualbox
.
manually by downloading the iso file inside VM (e.g. wget
) and installing it, e.g.
wget http://download.virtualbox.org/virtualbox/5.0.16/VBoxGuestAdditions_5.0.16.iso -P /tmp
sudo mount -o loop /tmp/VBoxGuestAdditions_5.0.16.iso /mnt
sudo sh -x /mnt/VBoxLinuxAdditions.run # --keep
Extra debug: cd ~/install && sh -x ./install.sh /mnt/VBoxLinuxAdditions.run
Double check that kernel extensions are up and running:
sudo modprobe vboxsf
Start/restart the service:
sudo /opt/VBoxGuestAdditions*/init/vboxadd setup
(add sudo sh -x
to debug)sudo /etc/init.d/vboxadd-service start
sudo /etc/init.d/vboxdrv setup
sudo service VBoxService start
If above didn't work, here are more sophisticated steps to fix it. This assumes that you've already VBoxGuestAdditions installed (as shown above).
The most common reason why mounting shared folder doesn't work may related to building Guest Additions module which failed. If in /var/log/vboxadd-install.log
you've the following error:
The headers for the current running kernel were not found.
this means either you didn't install kernel sources, or they cannot be found.
If you installed them already as instructed above, run this command:
$ sudo sh -x /opt/VBoxGuestAdditions-5.0.16/init/vboxadd setup 2>&1 | grep KERN
+ KERN_VER=2.6.32-573.18.1.el6.x86_64
+ KERN_DIR=/lib/modules/2.6.32-573.18.1.el6.x86_64/build
So basically vboxadd
script is expecting your kernel sources to be available at the following dir:
ls -la /lib/modules/$(uname -r)/build
Check if the kernel dir exists (symbolic link points to the existing folder). If it's not, please install them to the right folder (e.g. in /usr/src/kernels
).
So vboxadd
script can enter your kernel source directory and run make kernelrelease
, get the value and compare with your current kernel version.
Here is the logic:
KERN_VER=`uname -r`
KERN_DIR="/lib/modules/$KERN_VER/build"
if [ -d "$KERN_DIR" ]; then
KERN_REL=`make -sC $KERN_DIR --no-print-directory kernelrelease 2>/dev/null || true`
if [ -z "$KERN_REL" -o "x$KERN_REL" = "x$KERN_VER" ]; then
return 0
fi
fi
If the kernel version doesn't match with the sources, maybe you've to upgrade your Linux kernel (in case the sources are newer than your kernel).
Try:
vagrant plugin install vagrant-vbguest vagrant vbgues
If won't work, try the following manual steps for CentOS:
$ sudo yum update
$ sudo yum install kernel-$(uname -r) kernel-devel kernel-headers # or: reinstall
$ rpm -qf /lib/modules/$(uname -r)/build
kernel-2.6.32-573.18.1.el6.x86_64
$ ls -la /lib/modules/$(uname -r)/build
$ sudo reboot # and re-login
$ sudo ln -sv /usr/src/kernels/$(uname -r) /lib/modules/$(uname -r)/build
$ sudo /opt/VBoxGuestAdditions-*/init/vboxadd setup
Here is another method using MVC tools which you can handle requests to bad controller names, bad route names, and any other criteria you see fit inside of an Action method. Personally, I prefer to avoid as many web.config settings as possible, because they do the 302 / 200 redirect and do not support ResponseRewrite (Server.Transfer
) using Razor views. I'd prefer to return a 404 with a custom error page for SEO reasons.
Some of this is new take on cottsak's technique above.
This solution also uses minimal web.config settings favoring the MVC 3 Error Filters instead.
Just throw a HttpException from an action or custom ActionFilterAttribute.
Throw New HttpException(HttpStatusCode.NotFound, "[Custom Exception Message Here]")
Add the following setting to your web.config. This is required to use MVC's HandleErrorAttribute.
<customErrors mode="On" redirectMode="ResponseRedirect" />
Add a custom HandleHttpErrorAttribute similar to the MVC framework's HandleErrorAttribute, except for HTTP errors:
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Public Class HandleHttpErrorAttribute
Inherits FilterAttribute
Implements IExceptionFilter
Private Const m_DefaultViewFormat As String = "ErrorHttp{0}"
Private m_HttpCode As HttpStatusCode
Private m_Master As String
Private m_View As String
Public Property HttpCode As HttpStatusCode
Get
If m_HttpCode = 0 Then
Return HttpStatusCode.NotFound
End If
Return m_HttpCode
End Get
Set(value As HttpStatusCode)
m_HttpCode = value
End Set
End Property
Public Property Master As String
Get
Return If(m_Master, String.Empty)
End Get
Set(value As String)
m_Master = value
End Set
End Property
Public Property View As String
Get
If String.IsNullOrEmpty(m_View) Then
Return String.Format(m_DefaultViewFormat, Me.HttpCode)
End If
Return m_View
End Get
Set(value As String)
m_View = value
End Set
End Property
Public Sub OnException(filterContext As System.Web.Mvc.ExceptionContext) Implements System.Web.Mvc.IExceptionFilter.OnException
If filterContext Is Nothing Then Throw New ArgumentException("filterContext")
If filterContext.IsChildAction Then
Return
End If
If filterContext.ExceptionHandled OrElse Not filterContext.HttpContext.IsCustomErrorEnabled Then
Return
End If
Dim ex As HttpException = TryCast(filterContext.Exception, HttpException)
If ex Is Nothing OrElse ex.GetHttpCode = HttpStatusCode.InternalServerError Then
Return
End If
If ex.GetHttpCode <> Me.HttpCode Then
Return
End If
Dim controllerName As String = filterContext.RouteData.Values("controller")
Dim actionName As String = filterContext.RouteData.Values("action")
Dim model As New HandleErrorInfo(filterContext.Exception, controllerName, actionName)
filterContext.Result = New ViewResult With {
.ViewName = Me.View,
.MasterName = Me.Master,
.ViewData = New ViewDataDictionary(Of HandleErrorInfo)(model),
.TempData = filterContext.Controller.TempData
}
filterContext.ExceptionHandled = True
filterContext.HttpContext.Response.Clear()
filterContext.HttpContext.Response.StatusCode = Me.HttpCode
filterContext.HttpContext.Response.TrySkipIisCustomErrors = True
End Sub
End Class
Add Filters to the GlobalFilterCollection (GlobalFilters.Filters
) in Global.asax
. This example will route all InternalServerError (500) errors to the Error shared view (Views/Shared/Error.vbhtml
). NotFound (404) errors will be sent to ErrorHttp404.vbhtml in the shared views as well. I've added a 401 error here to show you how this can be extended for additional HTTP error codes. Note that these must be shared views, and they all use the System.Web.Mvc.HandleErrorInfo
object as a the model.
filters.Add(New HandleHttpErrorAttribute With {.View = "ErrorHttp401", .HttpCode = HttpStatusCode.Unauthorized})
filters.Add(New HandleHttpErrorAttribute With {.View = "ErrorHttp404", .HttpCode = HttpStatusCode.NotFound})
filters.Add(New HandleErrorAttribute With {.View = "Error"})
Create a base controller class and inherit from it in your controllers. This step allows us to handle unknown action names and raise the HTTP 404 error to our HandleHttpErrorAttribute.
Public Class BaseController
Inherits System.Web.Mvc.Controller
Protected Overrides Sub HandleUnknownAction(actionName As String)
Me.ActionInvoker.InvokeAction(Me.ControllerContext, "Unknown")
End Sub
Public Function Unknown() As ActionResult
Throw New HttpException(HttpStatusCode.NotFound, "The specified controller or action does not exist.")
Return New EmptyResult
End Function
End Class
Create a ControllerFactory override, and override it in your Global.asax file in Application_Start. This step allows us to raise the HTTP 404 exception when an invalid controller name has been specified.
Public Class MyControllerFactory
Inherits DefaultControllerFactory
Protected Overrides Function GetControllerInstance(requestContext As System.Web.Routing.RequestContext, controllerType As System.Type) As System.Web.Mvc.IController
Try
Return MyBase.GetControllerInstance(requestContext, controllerType)
Catch ex As HttpException
Return DependencyResolver.Current.GetService(Of BaseController)()
End Try
End Function
End Class
'In Global.asax.vb Application_Start:
controllerBuilder.Current.SetControllerFactory(New MyControllerFactory)
Include a special route in your RoutTable.Routes for the BaseController Unknown action. This will help us raise a 404 in the case where a user accesses an unknown controller, or unknown action.
'BaseController
routes.MapRoute( _
"Unknown", "BaseController/{action}/{id}", _
New With {.controller = "BaseController", .action = "Unknown", .id = UrlParameter.Optional} _
)
This example demonstrated how one can use the MVC framework to return 404 Http Error Codes to the browser without a redirect using filter attributes and shared error views. It also demonstrates showing the same custom error page when invalid controller names and action names are specified.
I'll add a screenshot of an invalid controller name, action name, and a custom 404 raised from the Home/TriggerNotFound action if I get enough votes to post one =). Fiddler returns a 404 message when I access the following URLs using this solution:
/InvalidController
/Home/InvalidRoute
/InvalidController/InvalidRoute
/Home/TriggerNotFound
cottsak's post above and these articles were good references.
I believe you need subexpressions. If I remember right you can use the normal ()
brackets for subexpressions.
This part is From grep manual:
Back References and Subexpressions
The back-reference \n, where n is a single digit, matches the substring
previously matched by the nth parenthesized subexpression of the
regular expression.
Do something like ^[^(abc)]
should do the trick.
There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).
getmtime(path)
Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.
stat(path)
Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), st_mtime (time of most recent content
modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.