One way could be to have an array of allowed character codes and then use the Array.includes
function to see if entered character is allowed.
Example:
<input type="text" onkeypress="return [45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57].includes(event.charCode);"/>
I pieced a few of the other posts together, as the workbench 'preferences' fix did not work for me. (WB 6.3)
SELECT CAST(`column` AS CHAR(10000) CHARACTER SET utf8) FROM `table`;
You need to await the GetAsync
method. It will then throw a TaskCanceledException
if it has timed out. Additionally, GetStringAsync
and GetStreamAsync
internally handle timeout, so they will NEVER throw.
string baseAddress = "http://localhost:8080/";
var client = new HttpClient()
{
BaseAddress = new Uri(baseAddress),
Timeout = TimeSpan.FromMilliseconds(1)
};
try
{
var s = await client.GetAsync();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException.Message);
}
Try:
$post = $wp_query->post;
Then pass the function:
$post->ID
I have a similar case: wanting my *.jar
file to access a file in a directory next to said *.jar
file. Refer to THIS ANSWER as well.
My file structure is:
./ - the root of your program
|__ *.jar
|__ dir-next-to-jar/some.txt
I'm able to load a file (say, some.txt
) to an InputStream inside the *.jar
file with the following:
InputStream stream = null;
try{
stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");
}
catch(Exception e) {
System.out.print("error file to stream: ");
System.out.println(e.getMessage());
}
Then do whatever you will with the stream
I have created an illustration that explains better than words, in my opinion:
I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com
To answer the question a bit more, OG
tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.
I had the same problem and it was due to me not declaring the blank object first at the top of my controller:
$scope.model = {}
<input ng-model="model.firstProperty">
Hope this will works for you!
See ?assign
.
> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
[1] 5
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:
array.length * array[0].length
I think it should be
import webbrowser
webbrowser.open('http://gatedin.com')
NOTE: make sure that you give http or https
if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE. here you are importing webbrowser library
I wouldn't push regular code into an exception block. Just check whether any rows exist that meet your condition, and proceed from there:
declare
any_rows_found number;
begin
select count(*)
into any_rows_found
from my_table
where rownum = 1 and
... other conditions ...
if any_rows_found = 1 then
...
else
...
end if;
Here are the steps:
It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),
I just want to explain my solving for the same problem.
my code before(given same error):
$arr2= ""; // this is the problem and solve by replace this $arr2 = array();
for($i=2;$i<count($arrdata);$i++){
$rowx = explode(" ",$arrdata[$i]);
$arr1= ""; // and this is too
for($x=0;$x<count($rowx);$x++){
if($rowx[$x]!=""){
$arr1[] = $rowx[$x];
}
}
$arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
$td .="<tr>";
for($j=0;$j<count($hcol)-1;$j++){
$td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
}
$td .="</tr>";
}
my code after and solved it:
$arr2= array(); //change this from $arr2="";
for($i=2;$i<count($arrdata);$i++){
$rowx = explode(" ",$arrdata[$i]);
$arr1=array(); //and this
for($x=0;$x<count($rowx);$x++){
if($rowx[$x]!=""){
$arr1[] = $rowx[$x];
}
}
$arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
$td .="<tr>";
for($j=0;$j<count($hcol)-1;$j++){
$td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
}
$td .="</tr>";
}
Thank's. Hope it's helped, and sorry if my english mess like boy's room :D
git checkout branch1
git fetch origin
git rebase -p origin/mainbranch
If there are merge conflicts, fix them. Then, continue the rebase process by running: git rebase –-continue
after the fixing you can commit and push your local branch to remote branch
git push origin branch1
There are no underline even I deleted 'text-decoration: none;' from your code. But I had a similar experience.
Then I added a Code
a{
text-decoration: none;
}
and
a:hover{
text-decoration: none;
}
So, try your code with :hover.
In my case I'm using Qt and had defined a QObject
subclass in a foo.cpp
(not .h
) file. The fix was to add #include "foo.moc"
at the end of foo.cpp
.
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
You can be also interested what updates are available for plugins. For that, you have to merge the data about installed plugins with information about updates available here https://updates.jenkins.io/current/update-center.json .
To parse the downloaded file as a JSON you have to read online the second line (which is huge).
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
You can use netstat command
netstat --listen
To display open ports and established TCP connections,
netstat -vatn
To display only open UDP ports try the following command:
netstat -vaun
i ran mvn generate-resources and then marked the /target/generated-resources folder as "sources" (Project Structure -> Project Settings -> Modules -> Select /target/generated-resources -> Click on blue "Sources" icon.
This one works for me:
return Paths.get(ClassLoader.getSystemResource(resourceName).toURI());
Use the createFromFormat
method:
$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);
UPDATE
I now recommend the use of Carbon
Assume your file looks like this and is named test.txt (space delimited):
1 2
3 4
5 6
7 8
Then:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title...")
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.
Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.
$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace CertificateValidation
{
public class CertificateValidationResult
{
public string Subject { get; internal set; }
public string Thumbprint { get; internal set; }
public DateTime Expiration { get; internal set; }
public DateTime ValidationTime { get; internal set; }
public bool IsValid { get; internal set; }
public bool Accepted { get; internal set; }
public string Message { get; internal set; }
public CertificateValidationResult()
{
ValidationTime = DateTime.UtcNow;
}
}
public static class CertificateValidator
{
private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();
public static CertificateValidationResult[] CertificateValidationResults
{
get
{
return certificateValidationResults.ToArray();
}
}
public static CertificateValidationResult LastCertificateValidationResult
{
get
{
CertificateValidationResult lastCertificateValidationResult = null;
certificateValidationResults.TryPeek(out lastCertificateValidationResult);
return lastCertificateValidationResult;
}
}
public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
StringBuilder certificateValidationMessage = new StringBuilder();
bool allowCertificate = true;
if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
{
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
{
certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
}
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
{
certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
{
certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);
if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
{
allowCertificate = false;
}
}
}
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
{
certificateValidationMessage.AppendLine("The remote certificate was not available.");
allowCertificate = false;
}
System.Console.WriteLine();
}
else
{
certificateValidationMessage.AppendLine("The remote certificate is valid.");
}
CertificateValidationResult certificateValidationResult = new CertificateValidationResult
{
Subject = certificate.Subject,
Thumbprint = certificate.GetCertHashString(),
Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
Accepted = allowCertificate,
Message = certificateValidationMessage.ToString()
};
certificateValidationResults.Push(certificateValidationResult);
return allowCertificate;
}
public static void SetDebugCertificateValidation()
{
ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
}
public static void SetDefaultCertificateValidation()
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
public static void ClearCertificateValidationResults()
{
certificateValidationResults.Clear();
}
}
}
'@
function Set-CertificateValidationMode
{
<#
.SYNOPSIS
Sets the certificate validation mode.
.DESCRIPTION
Set the certificate validation mode to one of three modes with the following behaviors:
Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
information is logged and can be retrieved from the certificate handler.
.EXAMPLE
Set-CertificateValidationMode Debug
.PARAMETER Mode
The mode for certificate validation.
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param
(
[Parameter()]
[ValidateSet('Default', 'CheckRevocationList', 'Debug')]
[string] $Mode
)
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
switch ($Mode)
{
'Debug'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
[CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
}
'CheckRevocationList'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
[CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
}
'Default'
{
[System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
[CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
}
}
}
}
function Clear-CertificateValidationResults
{
<#
.SYNOPSIS
Clears the collection of certificate validation results.
.DESCRIPTION
Clears the collection of certificate validation results.
.EXAMPLE
Get-CertificateValidationResults
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param()
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
[CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
Sleep -Milliseconds 20
}
}
function Get-CertificateValidationResults
{
<#
.SYNOPSIS
Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
.DESCRIPTION
Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
.EXAMPLE
Get-CertificateValidationResults
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param()
begin
{
$isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null
if ($isValidatorClassLoaded -eq $false)
{
Add-Type -TypeDefinition $CertificateValidatorClass
}
}
process
{
return [CertificateValidation.CertificateValidator]::CertificateValidationResults
}
}
function Test-WebUrl
{
<#
.SYNOPSIS
Tests and reports information about the provided web URL.
.DESCRIPTION
Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
.EXAMPLE
Test-WebUrl 'http://websitetotest.com/'
.EXAMPLE
'https://websitetotest.com/' | Test-WebUrl
.PARAMETER HostName
The Hostname to add to the back connection hostnames list.
.PARAMETER UseDefaultCredentials
If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[Uri] $Url,
[Parameter()]
[Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
[Parameter()]
[switch] $UseDefaultCredentials
)
process
{
[bool] $succeeded = $false
[string] $statusCode = $null
[string] $statusDescription = $null
[string] $message = $null
[int] $bytesReceived = 0
[Timespan] $timeTaken = [Timespan]::Zero
$timeTaken = Measure-Command `
{
try
{
[Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
$succeeded = $true
$statusCode = $response.StatusCode.ToString('D')
$statusDescription = $response.StatusDescription
$bytesReceived = $response.RawContent.Length
Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
}
catch [System.Net.WebException]
{
$message = $Error[0].Exception.Message
[System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response
if ($exceptionResponse -ne $null)
{
$statusCode = $exceptionResponse.StatusCode.ToString('D')
$statusDescription = $exceptionResponse.StatusDescription
$bytesReceived = $exceptionResponse.ContentLength
if ($statusCode -in '401', '403', '404')
{
$succeeded = $true
}
}
else
{
Write-Warning "$($Url.ToString()): $($message)"
}
}
}
return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
}
}
Set-CertificateValidationMode Debug
Clear-CertificateValidationResults
Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize
Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize
I have this problem on angular web applications after replace link https://fonts.googleapis.com/icon?family=Material+Icons in index.html to integrated version (npm install .... material-icons...). This works, but sometimes web application show that warning.
When warning is shown icons are not rendered for approximately 1 second, so user see badly rendered icons.
I don't have solution yet.
It happens because you call it before DOM has loaded. Firstly, create the element and add atrributes to it, then after DOM has loaded call it. In your case it should look like that:
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
window.onload = function() {
document.getElementById("CursorLayer");
}
I don't know how MVC is relevant, but if your ID is an integer, this BRE should do:
^[1-9][0-9]*$
If you want to match real numbers (floats) rather than integers, you need to handle the case above, along with normal decimal numbers (i.e. 2.5
or 3.3¯
), cases where your pattern is between 0 and 1 (i.e. 0.25
), as well as case where your pattern has a decimal part that is 0. (i.e. 2.0
). And while we're at it, we'll add support for leading zeros on integers (i.e. 005
):
^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$
Note that this second one is an Extended RE. The same thing can be expressed in Basic RE, but almost everything understands ERE these days. Let's break the expression down into parts that are easier to digest.
^(
The caret matches the null at the beginning of the line, so preceding your regex with a caret anchors it to the beginning of the line. The opening parenthesis is there because of the or-bar, below. More on that later.
0*[1-9][0-9]*(\.[0-9]+)?
This matches any integer or any floating point number above 1. So our 2.0
would be matched, but 0.25
would not. The 0*
at the start handles leading zeros, so 005 == 5
.
|
The pipe character is an "or-bar" in this context. For purposes of evaluation of this expression, It has higher precedence than everything else, and effectively joins two regular expressions together. Parentheses are used to group multiple expressions separated by or-bars.
And the second part:
0+\.[0-9]*[1-9][0-9]*
This matches any number that starts with one or more 0
characters (replace +
with *
to match zero or more zeros, i.e. .25
), followed by a period, followed by a string of digits that includes at least one that is not a 0
. So this matches everything above 0
and below 1
.
)$
And finally, we close the parentheses and anchor the regex to the end of the line with the dollar sign, just as the caret anchors to the beginning of the line.
Of course, if you let your programming language evaluate something numerically rather than try to match it against a regular expression, you'll save headaches and CPU.
actually, if you already know the property, this will do it...
for example:
<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>
var txt = "";
txt = getStyle(InterTabLink);
setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");
function setStyle(element, styleText){
if(element.style.setAttribute)
element.style.setAttribute("cssText", styleText );
else
element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
var styleText = element.getAttribute('style');
if(styleText == null)
return "";
if (typeof styleText == 'string') // !IE
return styleText;
else // IE
return styleText.cssText;
}
Note that this only works for inline styles... not styles you've specified through a class or something like that...
Other note: you may have to escape some characters in that replace statement, but you get the idea.
IIS 7 or IIS 8 or 8.5 version - if you are migrating from 2003 to 2012/2008 make sure web service are in application type instead virtual directory
df[df.col.str.contains("foo").fillna(False)]
try the following code :
In your controller :
function myCtrl ($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
];
$scope.data= $scope.units[0]; // Set by default the value "test1"
};
In your page :
<select ng-model="data" ng-options="opt as opt.label for opt in units ">
</select>
Any time you run rails g
, you can reverse it by running rails d
(destroy) to remove what you've generated. If you have already run rake db:migrate
, you will need to run rake db:rollback
before destroying :)
For one-dimensional arrays:
$array = (array)$class;
For multi-dimensional array:
function stdToArray($obj){
$reaged = (array)$obj;
foreach($reaged as $key => &$field){
if(is_object($field))$field = stdToArray($field);
}
return $reaged;
}
There is simple shorthand technique I use most of the times..
String op = new String;
for (int i : is)
{
op += candidatesArr[i-1]+",";
}
op = op.substring(0, op.length()-1);
You may want to explore the notion of namespaces. In Python, the module is the natural place for global data:
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions,
modname.itemname
.
A specific use of global-in-a-module is described here - How do I share global variables across modules?, and for completeness the contents are shared here:
The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
File: config.py
x = 0 # Default value of the 'x' configuration setting
File: mod.py
import config
config.x = 1
File: main.py
import config
import mod
print config.x
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
GPS Visualizer has an interface by which you can cut and paste a CSV file and convert it to kml:
http://www.gpsvisualizer.com/map_input?form=googleearth
Then use Google Earth. If you don't have Google Earth and want to display it online I found another nifty service that will plot kml files online:
You can also specify the font size relative to the base_size
included in themes such as theme_bw()
(where base_size
is 11) using the rel()
function.
For example:
ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
geom_point() +
theme_bw() +
theme(legend.text=element_text(size=rel(0.5)))
I updated answer of Morteza Ziaeemehr to a cleaner and better code, This will unzip a file provided within form into current directory using DIR.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' >
<title>Unzip</title>
<style>
body{
font-family: arial, sans-serif;
word-wrap: break-word;
}
.wrapper{
padding:20px;
line-height: 1.5;
font-size: 1rem;
}
span{
font-family: 'Consolas', 'courier new', monospace;
background: #eee;
padding:2px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php
if(isset($_GET['page']))
{
$type = $_GET['page'];
global $con;
switch($type)
{
case 'unzip':
{
$zip_filename =$_POST['filename'];
echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
echo "current dir: <span>" . __DIR__ . "</span><br>";
$zip = new ZipArchive;
$res = $zip->open(__DIR__ . '/' .$zip_filename);
if ($res === TRUE)
{
$zip->extractTo(__DIR__);
$zip->close();
echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
}
else
{
echo '<p style="color:red;">Zip file not found!</p><br>';
}
break;
}
}
}
?>
End Script.
</div>
<form name="unzip" id="unzip" role="form">
<div class="body bg-gray">
<div class="form-group">
<input type="text" name="filename" class="form-control" placeholder="File Name (with extension)"/>
</div>
</div>
</form>
<script type="application/javascript">
$("#unzip").submit(function(event) {
event.preventDefault();
var url = "function.php?page=unzip"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#unzip").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data.msg); // show response from the php script.
document.getElementById("unzip").reset();
}
});
return false; // avoid to execute the actual submit of the form
});
</script>
</body>
</html>
I got some smooth results with these. It flows smoothly between the 3 width ranges, like a continuous piecewise function.
@media screen and (min-width: 581px) and (max-width: 1760px){
#expandingHeader {
line-height:5.2vw;
font-size: 5.99vw;
}
#tagLine {
letter-spacing: .15vw;
font-size: 1.7vw;
line-height:1.0vw;
}
}
@media screen and (min-width: 1761px){
#expandingHeader {
line-height:.9em;
font-size: 7.03em;
}
#tagLine {
letter-spacing: .15vw;
font-size: 1.7vw;
line-height:1.0vw;
}
}
@media screen and (max-width: 580px){
#expandingHeader {
line-height:.9em;
font-size: 2.3em;
}
#tagLine {
letter-spacing: .1em;
font-size: .65em;
line-height: .10em;
}
}
I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -
select * from test where DATE(date) = '2014-03-19';
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
I wrote this simple helper function:
#include <locale> // tolower
string to_lower(string s) {
for(char &c : s)
c = tolower(c);
return s;
}
Usage:
string s = "TEST";
cout << to_lower("HELLO WORLD"); // output: "hello word"
cout << to_lower(s); // won't change the original variable.
It's already 2017, and you can now use Apache Commons Collections4
The usage:
for(Object obj : ListUtils.emptyIfNull(list1)){
// Do your stuff
}
You can do the same null-safe check to other Collection classes with CollectionUtils.emptyIfNull
.
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
A lot of these answers are simplistic, and if someone is beginning WPF, they may not know all of the "ins-and-outs", as it is more complicated than just telling someone "Use .ShowDialog()
!". But that is the method (not .Show()
) that you want to use in order to block use of the underlying window and to keep the code from continuing until the modal window is closed.
First, you need 2 WPF windows. (One will be calling the other.)
From the first window, let's say that was called MainWindow.xaml, in its code-behind will be:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
Then add your button to your XAML:
<Button Name="btnOpenModal" Click="btnOpenModal_Click" Content="Open Modal" />
And right-click the Click
routine, select "Go to definition". It will create it for you in MainWindow.xaml.cs:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
}
Within that function, you have to specify the other page using its page class. Say you named that other page "ModalWindow", so that becomes its page class and is how you would instantiate (call) it:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
ModalWindow modalWindow = new ModalWindow();
modalWindow.ShowDialog();
}
Say you have a value you need set on your modal dialog. Create a textbox and a button in the ModalWindow
XAML:
<StackPanel Orientation="Horizontal">
<TextBox Name="txtSomeBox" />
<Button Name="btnSaveData" Click="btnSaveData_Click" Content="Save" />
</StackPanel>
Then create an event handler (another Click
event) again and use it to save the textbox value to a public static variable on ModalWindow
and call this.Close()
.
public partial class ModalWindow : Window
{
public static string myValue = String.Empty;
public ModalWindow()
{
InitializeComponent();
}
private void btnSaveData_Click(object sender, RoutedEventArgs e)
{
myValue = txtSomeBox.Text;
this.Close();
}
}
Then, after your .ShowDialog()
statement, you can grab that value and use it:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
ModalWindow modalWindow = new ModalWindow();
modalWindow.ShowDialog();
string valueFromModalTextBox = ModalWindow.myValue;
}
Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.
The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.
C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes
Use the Responsive Design Tool using Ctrl + Shift + M.
Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!
-- Change DATABASE Default Collation
SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change TABLE Collation / Char Set
SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change COLUMN Collation / Char Set
SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';
best to use crypt for password storing in DB
example code :
$crypted_pass = crypt($password);
//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
echo("hello user!")
}
documentation :
with io.vavr
public static char[] alphanumericAlphabet() {
return CharSeq
.rangeClosed('0','9')
.appendAll(CharSeq.rangeClosed('a','z'))
.appendAll(CharSeq.rangeClosed('A','Z'))
.toCharArray();
}
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
There is no linguistic support to do what you're asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields()
to get an array of Field
), but depending on what you're trying to do, this may not be the best solution.
Here's a simple example to show only some of what reflection is capable of doing.
import java.lang.reflect.*;
public class DumpFields {
public static void main(String[] args) {
inspect(String.class);
}
static <T> void inspect(Class<T> klazz) {
Field[] fields = klazz.getDeclaredFields();
System.out.printf("%d fields:%n", fields.length);
for (Field field : fields) {
System.out.printf("%s %s %s%n",
Modifier.toString(field.getModifiers()),
field.getType().getSimpleName(),
field.getName()
);
}
}
}
The above snippet uses reflection to inspect all the declared fields of class String
; it produces the following output:
7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER
These are excerpts from the book:
Given a
Class
object, you can obtainConstructor
,Method
, andField
instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:
- You lose all the benefits of compile-time checking.
- The code required to perform reflective access is clumsy and verbose.
- Performance suffers.
As a rule, objects should not be accessed reflectively in normal applications at runtime.
There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.
Quick Fix for Development
For development, you could just disable the cache in Chrome Dev Tools (Disabling Chrome cache for website development). The cache disabling happens only if the dev tools dialog is open, so you need not worry about toggling this option every time you do regular browsing.
Note: Using 'urlArgs' is the proper solution in production so that users get the latest code. But it makes debugging difficult because chrome invalidates breakpoints with every refresh (because its a 'new' file being served each time).
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)
I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):
def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):
if low=='min':
low=min(s)
elif low=='abs':
low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
if hi=='max':
hi=max(s)
elif hi=='abs':
hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))
if center=='mid':
center=(max(s)+min(s))/2
elif center=='avg':
center=mean(s)
elif center=='median':
center=median(s)
s2=[x-center for x in s]
hi=hi-center
low=low-center
center=0.
r=[]
for x in s2:
if x<low:
r.append(0.)
elif x>hi:
r.append(1.)
else:
if x>=center:
r.append((x-center)/(hi-center)*0.5+0.5)
else:
r.append((x-low)/(center-low)*0.5+0.)
if insideout==True:
ir=[(1.-abs(z-0.5)*2.) for z in r]
r=ir
rr =[x-(x-0.5)*shrinkfactor for x in r]
return rr
This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:
#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]
It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:
#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]
So now "2" which is closest to the center, defined as "1" is the highest value.
Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.
pro swing:
But at the bottom line I wouldn't suggest to use 'pure' swing or swt ;-) There are several application frameworks for swing/swt out. Look here. The biggest players are netbeans (swing) and eclipse (swt). Another nice framework could be griffon and a nice 'set of components' is pivot (swing). Griffon is very interesting because it integrates a lot of libraries and not only swing; also pivot, swt, etc
You can do it in a less than a minute with Google Drive (and free, no hassles)
• Bulk Upload all your images on imgur.com
• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.
• Use http://TextMechanic.co to prepend and append each line with this:
Prefix : =image("
AND
Suffix : ", 1)
So that it looks like this =image("URL", 1)
• Copy All
• Paste it in Google Spreadsheet
• Voila!
References :
http://www.labnol.org/internet/images-in-google-spreadsheet/18167/
https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
if you just want to check if one or the other element are present you can use this custom helper
Handlebars.registerHelper('if_or', function(elem1, elem2, options) {
if (Handlebars.Utils.isEmpty(elem1) && Handlebars.Utils.isEmpty(elem2)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
like this
{{#if_or elem1 elem2}}
{{elem1}} or {{elem2}} are present
{{else}}
not present
{{/if_or}}
if you also need to be able to have an "or" to compare function return values I would rather add another property that returns the desired result.
The templates should be logicless after all!
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
You say:
when i do
nan - inf
i dont get-inf
i getnan
This is because any operation containing NaN
as an operand would return NaN
.
A comparison with NaN
would return an unordered result.
>>> float('Inf') == float('Inf')
True
>>> float('NaN') == float('NaN')
False
If you are looking to cobble together a quick utility with minimal effort, bash is good. For a wrapper round an application, bash is invaluable.
Anything that may have you coming back over and over to add improvements is probably (though not always) better suited to a language like Python as Bash code comprising over a 1000 lines gets very painful to maintain. Bash code is also irritating to debug when it gets long.......
Part of the problem with these kind of questions is, from my experience, that shell scripts are usually all custom tasks. There have been very few shell scripting tasks that I have come across where there is already a solution freely available.
The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:
1) null, meaning that no request has been sent yet
2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.
In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)
I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:
<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>
Then you can trigger all links with the .link
class attached as tooltips like so:
$('.link').tooltip()
Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel
attribute. With this attribute you can target all links or elements with the rel
property set to tooltip
, like so:
$('[rel=tooltip]').tooltip()
And your links would look like something like this:
<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>
Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:
$('#example').tooltip({
selector: "a[rel=tooltip]"
})
This selector will target all of your tooltips with the rel
attribute "within" your #example
div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
Create a new Swift file within your project, name it Reachability.swift. Cut & paste the following code into it to create your class.
import Foundation
import SystemConfiguration
open class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
you can call Reachability from anywhere of your code, just like
if Reachability.isConnectedToNetwork() {
print("Network is connected")
} else {
print("Network is not connected")
}
function addDays(n){_x000D_
var t = new Date();_x000D_
t.setDate(t.getDate() + n); _x000D_
var month = "0"+(t.getMonth()+1);_x000D_
var date = "0"+t.getDate();_x000D_
month = month.slice(-2);_x000D_
date = date.slice(-2);_x000D_
var date = date +"/"+month +"/"+t.getFullYear();_x000D_
alert(date);_x000D_
}_x000D_
_x000D_
addDays(5);
_x000D_
To be agnostic, drop back and punt.
Select a.name as a_name, r.name as r_name
from ApplicationsResource ar, Applications a, Resources r
where a.id = ar.app_id
and r.id = ar.resource_id
order by r.name, a.name;
Now user your server programming language to concatenate a_names while r_name is the same as the last time.
Just wanted to complete the thread. To be very clear this does not works in IE9, however we can do it by little css trick.
<div class="customselect">
<select>
<option>2000</option>
<option>2001</option>
<option>2002</option>
</select>
</div>
.customselect {
width: 80px;
overflow: hidden;
border:1px solid;
}
.customselect select {
width: 100px;
border:none;
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
}
Note that
You can configure Apache so that all files With .inc
extension are forbidden to be retrieved by visiting URL directly.
see link:https://serverfault.com/questions/22577/how-to-deny-the-web-access-to-some-files
In Python 3 this is the default behavior, but if you aren't using that you can import division like so:
>>> from __future__ import division
>>> 144/314
0.4585987261146497
Alternatively you can cast one of the variables to a float when doing your division which will do the same thing
sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))
There is no need to add any extra div wrapper as others suggest.
The simplest way is to wrap your input element inside a related label tag and set input style to display:block
.
Bonus point earned: now you don't need to set the labels for
attribute. Because every label target the nested input.
<form name="message" method="post">
<section>
<label class="left">
Name
<input id="name" type="text" name="name">
</label>
<label class="right">
Email
<input id="email" type="text" name="email">
</label>
</section>
</form>
Use the WINAPI CreateDirectory()
function to create a folder.
You can use this function without checking if the directory already exists as it will fail but GetLastError()
will return ERROR_ALREADY_EXISTS
:
if (CreateDirectory(OutputFolder.c_str(), NULL) ||
ERROR_ALREADY_EXISTS == GetLastError())
{
// CopyFile(...)
}
else
{
// Failed to create directory.
}
The code for constructing the target file is incorrect:
string(OutputFolder+CopiedFile).c_str()
this would produce "D:\testEmploi Nam.docx"
: there is a missing path separator between the directory and the filename. Example fix:
string(OutputFolder+"\\"+CopiedFile).c_str()
For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).
However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderDate >'20090515'
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
AND ORD.OrderDate >'20090515'
The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.
The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)
The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.
SELECT *
FROM dbo.Customers AS CUS
LEFT JOIN dbo.Orders AS ORD
ON CUS.CustomerID = ORD.CustomerID
WHERE ORD.OrderID is null
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
Simplest way to truly remove all non-numeric characters:
echo preg_replace('/\D/', '', $string);
\D
represents "any character that is not a decimal digit"
In Other ways to get difference between date;
import dateutil.parser
import datetime
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
Thanks
It's not a query waiting for connection; it's a connection pointer waiting for the timeout to terminate.
It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does.
The really worst case: It's using one connection of your pool; If you would connect multiple times via console client and just close the client without closing the connection, you could use up all your connections and have to wait for the timeout to be able to connect again... but this is highly unlikely :-)
See MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"? and https://dba.stackexchange.com/questions/1558/how-long-is-too-long-for-mysql-connections-to-sleep for more information.
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:
checkFileExistence= function (file){
result=false;
jQuery.ajaxSetup({async:false});
$.get(file)
.done(function() {
result=true;
})
.fail(function() {
result=false;
})
jQuery.ajaxSetup({async:true});
return(result);
},
Stop stomping on round
somewhere else by binding an int
to it.
Depending on how often you use this in your code you could consider the following:
macro
#define SIGN(x) ( (x) >= 0 )
Inline function
inline int sign(int x)
{
return x >= 0;
}
Then you would just go:
bigInt.sign = sign(number);
Here is another easier possibility to read in a json file:
#include "json/json.h"
std::ifstream file_input("input.json");
Json::Reader reader;
Json::Value root;
reader.parse(file_input, root);
cout << root;
You can then get the values like this:
cout << root["key"]
Android Studio 1.2.2 has moved the setting into the General
subfolder of Editor settings.
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
the problem was you have to set
Do you want to make this app and all its live features available to the general public?
set status and review
to ON
and problem solved
enjoy coding
With Keys and Values this works as well:
foreach ($array as $key => $value) {
if ($value === end($array)) {
echo "LAST ELEMENT!";
}
}
To do this efficiently using jQuery, you can chain it like so:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')
):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
Also (since there is a js tag), if you wanted to do it in vanilla js:
For modern browsers (See this to see which browsers I'm calling modern)
(assuming one element with class theClassThatsThereNow
)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
Or older browsers:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');
If you are working with Flutter then this command would definitely work for you.
flutter doctor --android-licenses
The command bellow wont work always. If you do just:
$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.
$ git reset --hard
HEAD is now at b05f611 Here the commit message bla, bla
$ git pull
Auto-merging thefile1.c
CONFLICT (content): Merge conflict in thefile1.c
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.
and so on...
To really start over, downloading thebranch and overwriting all your local changes, just do:
$ git checkout thebranch
$ git reset --hard origin/thebranch
This will work just fine.
$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.
$ git reset --hard origin/thebranch
HEAD is now at 7639058 Here commit message again...
$ git status
# On branch thebranch
nothing to commit (working directory clean)
$ git checkout thebranch
Already on 'thebranch'
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
Building up on @peeol's excellent answer, you can also remove the frame by doing
for spine in plt.gca().spines.values():
spine.set_visible(False)
To give an example (the entire code sample can be found at the end of this post), let's say you have a bar plot like this,
you can remove the frame with the commands above and then either keep the x-
and ytick
labels (plot not shown) or remove them as well doing
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
In this case, one can then label the bars directly; the final plot could look like this (code can be found below):
Here is the entire code that is necessary to generate the plots:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
xvals = list('ABCDE')
yvals = np.array(range(1, 6))
position = np.arange(len(xvals))
mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)
plt.title('My great data')
# plt.show()
# get rid of the frame
for spine in plt.gca().spines.values():
spine.set_visible(False)
# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
# plt.show()
# direct label each bar with Y axis values
for bari in mybars:
height = bari.get_height()
plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
ha='center', color='white', fontsize=15)
plt.show()
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);
It seems to me that the StringBuilder will be quick and efficient.
The basic form would look something like this:
public static String concatStrings(List<String> strings)
{
StringBuilder sb = new StringBuilder();
for(String s: strings)
{
sb.append(s);
}
return sb.toString();
}
If that's too simplistic (and it probably is), you can use a similar approach and add a separator like this:
public static String concatStringsWSep(List<String> strings, String separator)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < strings.size(); i++)
{
sb.append(strings.get(i));
if(i < strings.size() - 1)
sb.append(separator);
}
return sb.toString();
}
I agree with the others who have responded to this question when they say that you should not rely on the toString() method of Java's ArrayList.
You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.
Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method
I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());
when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.
Sometimes changing document.body.innerHTML
breaks some JS scripts on page. Here is version, that only changes content of text
elements:
function replace(element, from, to) {
if (element.childNodes.length) {
element.childNodes.forEach(child => replace(child, from, to));
} else {
const cont = element.textContent;
if (cont) element.textContent = cont.replace(from, to);
}
};
replace(document.body, new RegExp("hello", "g"), "hi");
Disclaimer: I don't do much C#
You are trying to modify the DictionaryEntry object which is stored in the HashTable. The Hashtable only stores one object -- your instance of DictionaryEntry. Changing the Key or the Value is enough to change the HashTable and cause the enumerator to become invalid.
You can do it outside of the loop:
if(hashtable.Contains(key))
{
hashtable[key] = value;
}
by first creating a list of all the keys of the values you wish to change and iterate through that list instead.
In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.
When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")
I think it can't read the files due to User Account Control.
I would like to expand on the ===
operator.
===
is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with ===
as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does ===
do?
===
is the pattern matching operator!
===
matches regular expressions===
checks range membership===
checks being instance of a class ===
calls lambda expressions===
sometimes checks equality, but mostly it does notSo how does this madness make sense?
Enumerable#grep
uses ===
internallycase when
statements use ===
internallyrescue
uses ===
internallyThat is why you can use regular expressions and classes and ranges and even lambda expressions in a case when
statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value
too, as well as with grep
method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]
You could just use ArrayList
which does the job for you.
If you are trying to access your web app which is running on apache tomcat server, it might be working perfect while you are trying to use it on http://localhost:8080/ , it will not work same if you are trying to access it on your mobile device browser for ex. chrome using http://192.168.x.x:8080/ so if you want to access via ip address on your remote/mobile device , do following settings
Change
<Connector connectionTimeout="20000" port="8080"protocol="HTTP/1.1" redirectPort="8443"/>
to.
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" address="0.0.0.0" />
You are good to go.
If you are on an English Windows machine, Git's default storage path will be C:\Documents and Settings\< current_user>\
, because on Windows the default Git local settings resides at C:\Documents and Settings\< current_user>\.git
and so Git creates a separate folder for each repo/clone
at C:\Documents and Settings\< current_user>\
and there are all the directories of cloned project.
For example, if you install Symfony 2 with
git clone git://github.com/symfony/symfony.git
the Symfony directory and file will be at
C:\Documents and Settings\< current_user>\symfony\
You only need to check if the form is dirty and valid before submitting it. Checkout the following code.
<form name="frmRegister" data-ng-submit="frmRegister.$valid && frmRegister.$dirty ? register() : return false;" novalidate>
And also you can disable your submit button with the following change:
<input type="submit" value="Save" data-ng-disable="frmRegister.$invalid || !frmRegister.$dirty" />
This should help for your initial
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
I believe what you're trying to do is impossible.
The junk that BinaryFormatter
creates is necessary to recover the object from the file after your program stopped.
However it is possible to get the object data, you just need to know the exact size of it (more difficult than it sounds) :
public static unsafe byte[] Binarize(object obj, int size)
{
var r = new byte[size];
var rf = __makeref(obj);
var a = **(IntPtr**)(&rf);
Marshal.Copy(a, r, 0, size);
return res;
}
this can be recovered via:
public unsafe static dynamic ToObject(byte[] bytes)
{
var rf = __makeref(bytes);
**(int**)(&rf) += 8;
return GCHandle.Alloc(bytes).Target;
}
The reason why the above methods don't work for serialization is that the first four bytes in the returned data correspond to a RuntimeTypeHandle
. The RuntimeTypeHandle
describes the layout/type of the object but the value of it changes every time the program is ran.
EDIT: that is stupid don't do that -->
If you already know the type of the object to be deserialized for certain you can switch those bytes for BitConvertes.GetBytes((int)typeof(yourtype).TypeHandle.Value)
at the time of deserialization.
Simple is cheap in web development. I recommend using empty string when removing a particular style
$(element).style.attr = ' ';
Here's how you would do it in Kotlin
fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
//your code here
}
In the solution it is mentioned - "One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described."
For avoiding this -
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():
It's not fully cross-browsers solution, but must work well in most modern browser.
<img src="image.jpg" />
<style>
img:hover {
/* Ch 23+, Saf 6.0+, BB 10.0+ */
-webkit-filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
/* FF 35+ */
filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
}
</style>
EXTERNAL DEMO PLAYGROUND
IN-HOUSE DEMO SNIPPET (source:simpl.info)
#container {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
filter: blur(5px)_x000D_
}_x000D_
_x000D_
.grayscale {_x000D_
filter: grayscale(1)_x000D_
}_x000D_
_x000D_
.saturate {_x000D_
filter: saturate(5)_x000D_
}_x000D_
_x000D_
.sepia {_x000D_
filter: sepia(1)_x000D_
}_x000D_
_x000D_
.multi {_x000D_
filter: blur(4px) invert(1) opacity(0.5)_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
<h1><a href="https://simpl.info/cssfilters/" title="simpl.info home page">simpl.info</a> CSS filters</h1>_x000D_
_x000D_
<img src="https://simpl.info/cssfilters/balham.jpg" alt="No filter: Balham High Road and a rainbow" />_x000D_
<img class="blur" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur filter: Balham High Road and a rainbow" />_x000D_
<img class="grayscale" src="https://simpl.info/cssfilters/balham.jpg" alt="Grayscale filter: Balham High Road and a rainbow" />_x000D_
<img class="saturate" src="https://simpl.info/cssfilters/balham.jpg" alt="Saturate filter: Balham High Road and a rainbow" />_x000D_
<img class="sepia" src="https://simpl.info/cssfilters/balham.jpg" alt="Sepia filter: Balham High Road and a rainbow" />_x000D_
<img class="multi" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur, invert and opacity filters: Balham High Road and a rainbow" />_x000D_
_x000D_
<p><a href="https://github.com/samdutton/simpl/blob/gh-pages/cssfilters" title="View source for this page on GitHub" id="viewSource">View source on GitHub</a></p>_x000D_
_x000D_
</div>
_x000D_
NOTES
RESOURCES:
I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:
ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin
. If the request is an ajax request, it will not call the super.form_valid
method, just call the form.save()
directly.
from django.http import JsonResponse
from django import forms
from django.db import models
class AjaxableResponseMixin(object):
success_return_code = 1
error_return_code = 0
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
form.errors.update({'result': self.error_return_code})
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
if self.request.is_ajax():
self.object = form.save()
data = {
'result': self.success_return_code
}
return JsonResponse(data)
else:
response = super(AjaxableResponseMixin, self).form_valid(form)
return response
class Product(models.Model):
name = models.CharField('product name', max_length=255)
class ProductAddForm(forms.ModelForm):
'''
Product add form
'''
class Meta:
model = Product
exclude = ['id']
class PriceUnitAddView(AjaxableResponseMixin, CreateView):
'''
Product add view
'''
model = Product
form_class = ProductAddForm
You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.
package com.example.package;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CustomLog4jAppender extends FileAppender {
private static final int TOP_OF_TROUBLE = -1;
private static final int TOP_OF_MINUTE = 0;
private static final int TOP_OF_HOUR = 1;
private static final int HALF_DAY = 2;
private static final int TOP_OF_DAY = 3;
private static final int TOP_OF_WEEK = 4;
private static final int TOP_OF_MONTH = 5;
private String datePattern = "'.'yyyy-MM-dd";
private String compressBackups = "false";
private String maxNumberOfDays = "7";
private String scheduledFilename;
private long nextCheck = System.currentTimeMillis() - 1;
private Date now = new Date();
private SimpleDateFormat sdf;
private RollingCalendar rc = new RollingCalendar();
private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
public CustomLog4jAppender() {
}
public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
super(layout, filename, true);
this.datePattern = datePattern;
activateOptions();
}
public void setDatePattern(String pattern) {
datePattern = pattern;
}
public String getDatePattern() {
return datePattern;
}
@Override
public void activateOptions() {
super.activateOptions();
if (datePattern != null && fileName != null) {
now.setTime(System.currentTimeMillis());
sdf = new SimpleDateFormat(datePattern);
int type = computeCheckPeriod();
printPeriodicity(type);
rc.setType(type);
File file = new File(fileName);
scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
} else {
LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
}
}
private void printPeriodicity(int type) {
String appender = "Log4J Appender: ";
switch (type) {
case TOP_OF_MINUTE:
LogLog.debug(appender + name + " to be rolled every minute.");
break;
case TOP_OF_HOUR:
LogLog.debug(appender + name + " to be rolled on top of every hour.");
break;
case HALF_DAY:
LogLog.debug(appender + name + " to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug(appender + name + " to be rolled at midnight.");
break;
case TOP_OF_WEEK:
LogLog.debug(appender + name + " to be rolled at start of week.");
break;
case TOP_OF_MONTH:
LogLog.debug(appender + name + " to be rolled at start of every month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
private int computeCheckPeriod() {
RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
Date epoch = new Date(0);
if (datePattern != null) {
for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
simpleDateFormat.setTimeZone(gmtTimeZone);
String r0 = simpleDateFormat.format(epoch);
rollingCalendar.setType(i);
Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
String r1 = simpleDateFormat.format(next);
if (!r0.equals(r1)) {
return i;
}
}
}
return TOP_OF_TROUBLE;
}
private void rollOver() throws IOException {
if (datePattern == null) {
errorHandler.error("Missing DatePattern option in rollOver().");
return;
}
String datedFilename = fileName + sdf.format(now);
if (scheduledFilename.equals(datedFilename)) {
return;
}
this.closeFile();
File target = new File(scheduledFilename);
if (target.exists()) {
Files.delete(target.toPath());
}
File file = new File(fileName);
boolean result = file.renameTo(target);
if (result) {
LogLog.debug(fileName + " -> " + scheduledFilename);
} else {
LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
}
try {
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
} catch (IOException e) {
errorHandler.error("setFile(" + fileName + ", false) call failed.");
}
scheduledFilename = datedFilename;
}
@Override
protected void subAppend(LoggingEvent event) {
long n = System.currentTimeMillis();
if (n >= nextCheck) {
now.setTime(n);
nextCheck = rc.getNextCheckMillis(now);
try {
cleanupAndRollOver();
} catch (IOException ioe) {
LogLog.error("cleanupAndRollover() failed.", ioe);
}
}
super.subAppend(event);
}
public String getCompressBackups() {
return compressBackups;
}
public void setCompressBackups(String compressBackups) {
this.compressBackups = compressBackups;
}
public String getMaxNumberOfDays() {
return maxNumberOfDays;
}
public void setMaxNumberOfDays(String maxNumberOfDays) {
this.maxNumberOfDays = maxNumberOfDays;
}
protected void cleanupAndRollOver() throws IOException {
File file = new File(fileName);
Calendar cal = Calendar.getInstance();
int maxDays = 7;
try {
maxDays = Integer.parseInt(getMaxNumberOfDays());
} catch (Exception e) {
// just leave it at 7.
}
cal.add(Calendar.DATE, -maxDays);
Date cutoffDate = cal.getTime();
if (file.getParentFile().exists()) {
File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
int nameLength = file.getName().length();
for (File value : Optional.ofNullable(files).orElse(new File[0])) {
String datePart;
try {
datePart = value.getName().substring(nameLength);
Date date = sdf.parse(datePart);
if (date.before(cutoffDate)) {
Files.delete(value.toPath());
} else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
zipAndDelete(value);
}
} catch (Exception pe) {
// This isn't a file we should touch (it isn't named correctly)
}
}
}
rollOver();
}
private void zipAndDelete(File file) throws IOException {
if (!file.getName().endsWith(".zip")) {
File zipFile = new File(file.getParent(), file.getName() + ".zip");
try (FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[4096];
while (true) {
int bytesRead = fis.read(buffer);
if (bytesRead == -1) {
break;
} else {
zos.write(buffer, 0, bytesRead);
}
}
zos.closeEntry();
}
Files.delete(file.toPath());
}
}
class StartsWithFileFilter implements FileFilter {
private String startsWith;
private boolean inclDirs;
StartsWithFileFilter(String startsWith, boolean includeDirectories) {
super();
this.startsWith = startsWith.toUpperCase();
inclDirs = includeDirectories;
}
public boolean accept(File pathname) {
if (!inclDirs && pathname.isDirectory()) {
return false;
} else {
return pathname.getName().toUpperCase().startsWith(startsWith);
}
}
}
class RollingCalendar extends GregorianCalendar {
private static final long serialVersionUID = -3560331770601814177L;
int type = CustomLog4jAppender.TOP_OF_TROUBLE;
RollingCalendar() {
super();
}
RollingCalendar(TimeZone tz, Locale locale) {
super(tz, locale);
}
void setType(int type) {
this.type = type;
}
long getNextCheckMillis(Date now) {
return getNextCheckDate(now).getTime();
}
Date getNextCheckDate(Date now) {
this.setTime(now);
switch (type) {
case CustomLog4jAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MINUTE, 1);
break;
case CustomLog4jAppender.TOP_OF_HOUR:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.HOUR_OF_DAY, 1);
break;
case CustomLog4jAppender.HALF_DAY:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
int hour = get(Calendar.HOUR_OF_DAY);
if (hour < 12) {
this.set(Calendar.HOUR_OF_DAY, 12);
} else {
this.set(Calendar.HOUR_OF_DAY, 0);
this.add(Calendar.DAY_OF_MONTH, 1);
}
break;
case CustomLog4jAppender.TOP_OF_DAY:
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.DATE, 1);
break;
case CustomLog4jAppender.TOP_OF_WEEK:
this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.WEEK_OF_YEAR, 1);
break;
case CustomLog4jAppender.TOP_OF_MONTH:
this.set(Calendar.DATE, 1);
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MONTH, 1);
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
}
return getTime();
}
}
}
And use this properties in your log4j config file:
log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true
To change the end address property edit your wsdl file
<wsdl:definitions.......
<wsdl:service name="serviceMethodName">
<wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
<soap:address location="http://service_end_point_adress"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
I had the same problem and in order to execute pip install inside virtualenv I had to use this command:
RUN pip install virtualenv virtualenvwrapper
RUN mkdir -p /opt/virtualenvs
ENV WORKON_HOME /opt/virtualenvs
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh \
&& mkvirtualenv myapp \
&& workon myapp \
&& pip install -r /mycode/myapp/requirements.txt"
I hope it helps.
I too faced the same issue. I followed the following steps to resolve my issue -
If the above steps don't work for you, instead of Workspace default JRE, you can choose an Alternate JRE and give the path to the JRE that you want to point.
After a quick google:
__STDC__
and __STDC_VERSION__
, see here
Here is a way so that when you select an option, it turns black. When you change it back to the placeholder, it turns back into the placeholder color (in this case red).
http://jsfiddle.net/wFP44/166/
It requires the options to have values.
$('select').on('change', function() {_x000D_
if ($(this).val()) {_x000D_
return $(this).css('color', 'black');_x000D_
} else {_x000D_
return $(this).css('color', 'red');_x000D_
}_x000D_
});
_x000D_
select{_x000D_
color: red;_x000D_
}_x000D_
select option { color: black; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value="">Pick one...</option>_x000D_
<option value="test1">Test 1</option>_x000D_
<option value="test2">Test 2</option>_x000D_
<option value="test3">Test 3</option>_x000D_
</select>
_x000D_
Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.
Installation
npm install --save-dev unminified-webpack-plugin
Usage
var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new UnminifiedWebpackPlugin()
]
};
By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
Just set the height and width where you are adding that logo. I tried and its working fine
Check if element's ID is exist
if ($('#id').attr('id') == 'id')_x000D_
{_x000D_
//OK_x000D_
}
_x000D_
You can download the 10.7 Lion JDK from http://connect.apple.com.
Sign in and click the java
section on the right.
The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.
At the time of writing the JDK ended up here:
/Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
Open up eclipse preferences and go to Java --> Installed JREs page
Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location
At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button
From the Add JRE wizard choose "MacOS X VM" for the JRE Type
For the JRE Definition Page we need to fill in the following:
The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:
Finish the wizard and return to the Installed JREs page
Choose "System JDK" from the list
You can now develop normally with:
I found a solution for animate hiding cells in static table.
// Class for wrapping Objective-C block
typedef BOOL (^HidableCellVisibilityFunctor)();
@interface BlockExecutor : NSObject
@property (strong,nonatomic) HidableCellVisibilityFunctor block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block;
@end
@implementation BlockExecutor
@synthesize block = _block;
+ (BlockExecutor*)executorWithBlock:(HidableCellVisibilityFunctor)block
{
BlockExecutor * executor = [[BlockExecutor alloc] init];
executor.block = block;
return executor;
}
@end
Only one additional dictionary needed:
@interface MyTableViewController ()
@property (nonatomic) NSMutableDictionary * hidableCellsDict;
@property (weak, nonatomic) IBOutlet UISwitch * birthdaySwitch;
@end
And look at implementation of MyTableViewController. We need two methods to convert indexPath between visible and invisible indexes...
- (NSIndexPath*)recoverIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row <= indexPath.row + rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row+rowDelta inSection:indexPath.section];
}
- (NSIndexPath*)mapToNewIndexPath:(NSIndexPath *)indexPath
{
int rowDelta = 0;
for (NSIndexPath * ip in [[self.hidableCellsDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:ip];
if (ip.section == indexPath.section
&& ip.row < indexPath.row - rowDelta
&& !executor.block())
{
rowDelta++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row-rowDelta inSection:indexPath.section];
}
One IBAction on UISwitch value changing:
- (IBAction)birthdaySwitchChanged:(id)sender
{
NSIndexPath * indexPath = [self mapToNewIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
if (self.birthdaySwitch.on)
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
else
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
Some UITableViewDataSource and UITableViewDelegate methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int numberOfRows = [super tableView:tableView numberOfRowsInSection:section];
for (NSIndexPath * indexPath in [self.hidableCellsDict allKeys])
if (indexPath.section == section)
{
BlockExecutor * executor = [self.hidableCellsDict objectForKey:indexPath];
numberOfRows -= (executor.block()?0:1);
}
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPath = [self recoverIndexPath:indexPath];
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// initializing dictionary
self.hidableCellsDict = [NSMutableDictionary dictionary];
[self.hidableCellsDict setObject:[BlockExecutor executorWithBlock:^(){return self.birthdaySwitch.on;}] forKey:[NSIndexPath indexPathForRow:1 inSection:1]];
}
- (void)viewDidUnload
{
[self setBirthdaySwitch:nil];
[super viewDidUnload];
}
@end
If You want to ensure, that your code is running with python2 and python3, use function input () in your script and add this to begin of your script:
from sys import version_info
if version_info.major == 3:
pass
elif version_info.major == 2:
try:
input = raw_input
except NameError:
pass
else:
print ("Unknown python version - input function not safe")
You could use the ternary operator:
return string.IsNullOrEmpty(strTestString) ? "0" : strTestString
FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
No, there isn't one - you have a couple of options:
Wrap the whole script in a big if/end block that is simply ensured to not be true (i.e. "if 1=2 begin" - this will only work however if the script doesn't include any GO statements (as those indicate a new batch)
Use the return statement at the top (again, limited by the batch separators)
Use a connection based approach, which will ensure non-execution for the entire script (entire connection to be more accurate) - use something like a 'SET PARSEONLY ON' or 'SET NOEXEC ON' at the top of the script. This will ensure all statements in the connection (or until said set statement is turned off) will not execute and will instead be parsed/compiled only.
Use a comment block to comment out the entire script (i.e. /* and */)
EDIT: Demonstration that the 'return' statement is batch specific - note that you will continue to see result-sets after the returns:
select 1
return
go
select 2
return
select 3
go
select 4
return
select 5
select 6
go
When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:
SELECT object_name(16003073)
EDIT :
There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/
if you want to access this programatically, you can do it by figuring out the version of eclipse\plugins\org.eclipse.platform_ plugin
String platformFile = <the above file>; //actually directory
versionPattern = Pattern.compile("\\d\\.\\d\\.\\d");
Matcher m = versionPattern.matcher(platformFile);
return m.group();
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";
That is a working configuration.
try to replace what you have
If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.
Ctrl+Z
(suspend the process)
bg
(restart the process in the background
disown %1
(assuming this is job #1, use jobs
to determine)
This solution provides CONVERT_IMPLICIT operation for your condition in predicate
SELECT *
FROM xxx
WHERE CAST(dates AS date) BETWEEN '1/1/2013' and '1/2/2013'
OR
SELECT *
FROM xxx
WHERE CONVERT(date, dates, 101) BETWEEN '1/1/2013' and '1/2/2013'
Demo on SQLFiddle
The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")
check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print
And if you have more than two lists to concatenate:
import operator
from functools import reduce # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])
# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)
It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args
.
There is, however, no guarantee that the output of SDTOUT
and STDERR
are interweaved line-by-line in timely order, using the POSIX
redirect merge syntax.
If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.
A dedicated console output logger (I.e. the "StdOut/StdErr Logger"
by 'LoRd MuldeR'
) may be more reliable for such a task.
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
CLOB are like Files, you can read parts of it easily like this
// read the first 1024 characters
String str = myClob.getSubString(0, 1024);
and you can overwrite to it like this
// overwrite first 1024 chars with first 1024 chars in str
myClob.setString(0, str,0,1024);
I don't suggest using StringBuilder and fill it until you get an Exception, almost like adding numbers blindly until you get an overflow. Clob is like a text file and the best way to read it is using a buffer, in case you need to process it, otherwise you can stream it into a local file like this
int s = 0;
File f = new File("out.txt");
FileWriter fw new FileWriter(f);
while (s < myClob.length())
{
fw.write(myClob.getSubString(0, 1024));
s += 1024;
}
fw.flush();
fw.close();
Another Javascript Solution
for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){
if(typeof obj[keys[i]] === 'undefined'){
delete obj[keys[i]];
}
}
No additional hasOwnProperty
check is required as Object.keys
does not look up the prototype chain and returns only the properties of obj
.
To update a little bit Brian's answer, there is now a nice backport of inspect.signature
that you can use in older python versions: funcsigs
.
So my personal preference would go for
try: # python 3.3+
from inspect import signature
except ImportError:
from funcsigs import signature
def aMethod(arg1, arg2):
pass
sig = signature(aMethod)
print(sig)
For fun, if you're interested in playing with Signature
objects and even creating functions with random signatures dynamically you can have a look at my makefun
project.
@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the +
operator fails for strings in EL (which is correct), then just do:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do:
<c:out value="${resp}${test}" />
Here is my code:
$('body').css('background-image', 'url("/apo/1.jpg")');
Enjoy, friend
It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:
testSpace.Attributes.Add("style", "text-align: center;");
or
testSpace.Attributes.Add("class", "centerIt");
or
testSpace.Attributes["style"] = "text-align: center;";
or
testSpace.Attributes["class"] = "centerIt";
try
{
string AppPath = "\\\\spri11U1118\\SampleBatch\\Bin\\";
string strFilePath = AppPath + "ABCED120D_XXX.bat";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = strFilePath;
string pwd = "s44erver";
proc.StartInfo.Domain = "abcd";
proc.StartInfo.UserName = "sysfaomyulm";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pwd)
secret.AppendChar(c);
proc.StartInfo.Password = secret;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = "psexec \\\\spri11U1118\\SampleBatch\\Bin ";
proc.Start();
while (!proc.HasExited)
{
proc.Refresh();
// Thread.Sleep(1000);
}
proc.Close();
}
catch (Exception ex)
{
throw ex;
}
ALL_TAB_COLUMNS
should be queryable from PL/SQL. DESC
is a SQL*Plus command.
SQL> desc all_tab_columns;
Name Null? Type
----------------------------------------- -------- ----------------------------
OWNER NOT NULL VARCHAR2(30)
TABLE_NAME NOT NULL VARCHAR2(30)
COLUMN_NAME NOT NULL VARCHAR2(30)
DATA_TYPE VARCHAR2(106)
DATA_TYPE_MOD VARCHAR2(3)
DATA_TYPE_OWNER VARCHAR2(30)
DATA_LENGTH NOT NULL NUMBER
DATA_PRECISION NUMBER
DATA_SCALE NUMBER
NULLABLE VARCHAR2(1)
COLUMN_ID NUMBER
DEFAULT_LENGTH NUMBER
DATA_DEFAULT LONG
NUM_DISTINCT NUMBER
LOW_VALUE RAW(32)
HIGH_VALUE RAW(32)
DENSITY NUMBER
NUM_NULLS NUMBER
NUM_BUCKETS NUMBER
LAST_ANALYZED DATE
SAMPLE_SIZE NUMBER
CHARACTER_SET_NAME VARCHAR2(44)
CHAR_COL_DECL_LENGTH NUMBER
GLOBAL_STATS VARCHAR2(3)
USER_STATS VARCHAR2(3)
AVG_COL_LEN NUMBER
CHAR_LENGTH NUMBER
CHAR_USED VARCHAR2(1)
V80_FMT_IMAGE VARCHAR2(3)
DATA_UPGRADED VARCHAR2(3)
HISTOGRAM VARCHAR2(15)
Edit: You have to import
#import <QuartzCore/QuartzCore.h>
for using corner radius.
Try this it will work for sure
UITextView* txtView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
txtView.layer.cornerRadius = 5.0;
txtView.clipsToBounds = YES;
As
Rob figured it out setting the if you want the border color to be similar as UITextField
then you need to change the border width to 2.0 and color to gray by adding the following line
[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[textView.layer setBorderWidth:2.0];
To get the cell value, you need to read it directly from DataGridView1
using e.RowIndex
and e.ColumnIndex
properties.
Eg:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If IsDBNull(value) Then
TextBox1.Text = "" ' blank if dbnull values
Else
TextBox1.Text = CType(value, String)
End If
End Sub
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME EXPRESSION for item in some_iterable]
which is shorter and sometimes clearer. Usually you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
twod_list = [] \
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /
AndroidManifest.xml
example:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<!--<category android:name="android.intent.category.LAUNCHER"/>-->
</intent-filter>
</activity>
<activity-alias android:label="RED"
android:icon="@drawable/ic_android_red"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
android:enabled="true"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias android:label="GREEN"
android:icon="@drawable/ic_android_green"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
android:enabled="false"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias android:label="BLUE"
android:icon="@drawable/ic_android_blue"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
android:enabled="false"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
</application>
Then follow below given code in MainActivity
:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
int imageResourceId;
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
int hours = new Time(System.currentTimeMillis()).getHours();
Log.d("DATE", "onCreate: " + hours);
getPackageManager().setComponentEnabledSetting(
getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
if(hours == 13)
{
imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}else if(hours == 14)
{
imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}else
{
imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
imageView.setImageResource(imageResourceId);
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
Sometimes you just want a simple one liner:
binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])
Python 3
use this:
this.permissionChanged = function (obj, event) {
if (event.type != "load") {
}
}
One of my friends had asked me this same question in university today (his requirements was to generate a random number between 1 & -1). So I wrote this, and it works fine so far with my testing. There are ideally a lot of ways to generate random numbers given a range. Try this:
Function:
private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{
if (numberOne == numberTwo){
throw new Exception("Both the numbers can not be equal");
}
float rand = (float) Math.random();
float highRange = Math.max(numberOne, numberTwo);
float lowRange = Math.min(numberOne, numberTwo);
float lowRand = (float) Math.floor(rand-1);
float highRand = (float) Math.ceil(rand+1);
float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;
return genRand;
}
Execute like this:
System.out.println( getRandomNumberBetween(1,-1));
My solution breaks the number in to an array of strings, adds zeros to each element based on its position relative to the length of the array, converts the new strings with zeros to roman numerals, and then joins them back together. This will only work with numbers up to 3999:
function convertToRoman(num){
var rnumerals = { 1 : 'I', 2 : 'II', 3 : 'III', 4 : 'IV', 5 : 'V', 6 : 'VI', 7 : 'VII',
8 : 'VIII', 9 : 'IX', 10 : 'X', 20 : 'XX', 30 : 'XXX', 40 : 'XL', 50 : 'L',
60 : 'LX', 70 : 'LXX', 80 : 'LXXX', 90 : 'XC', 100 : 'C', 200 : 'CC', 300 : 'CCC',
400 : 'CD', 500 : 'D', 600 : 'DC', 700 : 'DCC', 800 : 'DCCC', 900 : 'CM',
1000: 'M', 2000: 'MM', 3000: 'MMM'};
var zeros, romNum;
var arr = num.toString().split("");
var romArr = [];
for(var i=0; i < arr.length; i++){
zeros = "0".repeat((arr.length - i - 1));
arr[i] = arr[i].concat(zeros);
romArr.push(rnumerals[(arr[i])]);
}
romNum = romArr.join('');
return romNum;
}
For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there
If you have access to the server then you can use
select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null
For full details see port number of SQL Server
I would say you don't need to have the DEFAULT CURRENT_TIMESTAMP on your ts_update: if it is empty, then it is not updated, so your 'last update' is the ts_create.
Try the commons collections API:
List<Cat> bigList = ....; // master list
Collection<Cat> smallList = CollectionUtils.select(bigList, new Predicate() {
public boolean evaluate(Object o) {
Cat c = (Cat)o;
return c.getFavoriteFood().equals("Wiskas")
&& c.getWhateverElse().equals(Something);
}
});
Of course you don't have to use an anonymous class every time, you could create implementations of the Predicate
interface for commonly used searchs.
Have a Table class whose rows is a list of dict or better row objects
In table do not directly add rows but have a method which update few lookup maps e.g. for name if you are not adding rows in order or id are not consecutive you can have idMap too e.g.
class Table(object):
def __init__(self):
self.rows = []# list of row objects, we assume if order of id
self.nameMap = {} # for faster direct lookup for row by name
def addRow(self, row):
self.rows.append(row)
self.nameMap[row['name']] = row
def getRow(self, name):
return self.nameMap[name]
table = Table()
table.addRow({'ID':1,'name':'a'})
If all you want is a simple excel worksheet try this:
header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);
$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet 1</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo/>
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';
echo $data;
The key here is the xml data. This will keep excel from complaining about the file.
You can override the hover effect for devices that don't support hover. Like:
.my-thing {
color: #BADA55;
}
.my-thing:hover {
color: hotpink;
}
@media (hover: none) {
.my-thing {
color: #BADA55;
}
}
Tested and verified on iOS 12
Hat tip to https://stackoverflow.com/a/50285058/178959 for pointing this out.
This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");
I think you can use MDC to change logging level programmatically. The code below is an example to change logging level on current thread. This approach does not create dependency to logback implementation (SLF4J API contains MDC).
<configuration>
<turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter">
<Key>LOG_LEVEL</Key>
<DefaultThreshold>DEBUG</DefaultThreshold>
<MDCValueLevelPair>
<value>TRACE</value>
<level>TRACE</level>
</MDCValueLevelPair>
<MDCValueLevelPair>
<value>DEBUG</value>
<level>DEBUG</level>
</MDCValueLevelPair>
<MDCValueLevelPair>
<value>INFO</value>
<level>INFO</level>
</MDCValueLevelPair>
<MDCValueLevelPair>
<value>WARN</value>
<level>WARN</level>
</MDCValueLevelPair>
<MDCValueLevelPair>
<value>ERROR</value>
<level>ERROR</level>
</MDCValueLevelPair>
</turboFilter>
......
</configuration>
MDC.put("LOG_LEVEL", "INFO");
You should use TryParse method which Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
int intParsed;
if(int.TryParse(txtMyText.Text.Trim(),out intParsed))
{
// perform your code
}
If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu
under jQuery, and I place everything there.
The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.
Also, for convenience, I usually sub-space the plugin namespace with an i
namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.
This is how it works:
// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();
Now I can just do $.miniMenu.i.globalVar = 3
or $.miniMenu.i.parseSomeStuff = function(...) {...}
whenever I need to save something globally, and I still keep it out of the global namespace.
Setters and getters in Swift apply to computed properties/variables. These properties/variables are not actually stored in memory, but rather computed based on the value of stored properties/variables.
See Apple's Swift documentation on the subject: Swift Variable Declarations.
use parseInt
var total = parseInt(a) + parseInt(b);
$('#total_price').val(total);
If you want an easy-to-use way to add icons automatically when building locally (cordova emulate ios
, cordova run android
, etc) have a look at this gist:
https://gist.github.com/LinusU/7515016
Hopefully this will start to work out of the box sometime in the future, here is the relevant bug report on the Cordova project:
This splits the Seatblocks by space and gives each its own row.
In [43]: df
Out[43]:
CustNum CustomerName ItemQty Item Seatblocks ItemExt
0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60
1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300
In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()
In [45]: s.index = s.index.droplevel(-1) # to line up with df's index
In [46]: s.name = 'Seatblocks' # needs a name to join
In [47]: s
Out[47]:
0 2:218:10:4,6
1 1:13:36:1,12
1 1:13:37:1,13
Name: Seatblocks, dtype: object
In [48]: del df['Seatblocks']
In [49]: df.join(s)
Out[49]:
CustNum CustomerName ItemQty Item ItemExt Seatblocks
0 32363 McCartney, Paul 3 F04 60 2:218:10:4,6
1 31316 Lennon, John 25 F01 300 1:13:36:1,12
1 31316 Lennon, John 25 F01 300 1:13:37:1,13
Or, to give each colon-separated string in its own column:
In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))
Out[50]:
CustNum CustomerName ItemQty Item ItemExt 0 1 2 3
0 32363 McCartney, Paul 3 F04 60 2 218 10 4,6
1 31316 Lennon, John 25 F01 300 1 13 36 1,12
1 31316 Lennon, John 25 F01 300 1 13 37 1,13
This is a little ugly, but maybe someone will chime in with a prettier solution.
It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.
//a[contains(text(),'JB-')]
I know I'm a bit late to the party, but if you can put up with having the lines left-justified, one hack is to put the pipes before the items and then put a mask over the left edge, basically like so:
li::before {
content: " | ";
white-space: nowrap;
}
ul, li {
display: inline;
}
.mask {
width:4px;
position: absolute;
top:8px; //position as needed
}
more complete example: http://jsbin.com/hoyaduxi/1/edit
This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
Then you can add a base controller.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
In you controller, you would do:
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}
Try :
<template>
<th :class="'initial '+ active" v-on="click: myFilter">
<span class="wkday">M</span>
</th>
</template>
<script lang="ts">
active:string=''
myFilter(){
this.active='active'
}
</script>
<style>
.active{
/***your action***/
}
</style>
For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:
Add a couple of globals:
var clickms = 100;
var lastTouchDown = -1;
Then modify the switch statement from the original to this:
var d = new Date();
switch(event.type)
{
case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
case "touchmove": type="mousemove"; lastTouchDown = -1; break;
case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
default: return;
}
You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
Are you sure you don't want to actually merge the branches? If the working branch has some recent commits you don't want, you can just create a new branch with a HEAD at the point you want.
Now, if you really do want to cherry-pick a range of commits, for whatever reason, an elegant way to do this is to just pull of a patchset and apply it to your new integration branch:
git format-patch A..B
git checkout integration
git am *.patch
This is essentially what git-rebase is doing anyway, but without the need to play games. You can add --3way
to git-am
if you need to merge. Make sure there are no other *.patch files already in the directory where you do this, if you follow the instructions verbatim...
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
This means that the first parameter you passed is a boolean (true or false).
The first parameter is $result
, and it is false
because there is a syntax error in the query.
" ... WHERE PartNumber = $partid';"
You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)
You should escape the variable:
" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"
Or better, use Prepared Statements
.
Old question but nobody mentioned that it should be replaced by variable length arrays.
char arr[size];
instead of
char *arr=alloca(size);
It's in the standard C99 and existed as compiler extension in many compilers.
Adding the following line to the top of your .py file:
# -*- coding: utf-8 -*-
allows you to encode strings directly in your script, like this:
utfstr = "????"
The Python approach to "main" is almost unique to the language(*).
The semantics are a bit subtle. The __name__
identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__
is set to "__main__"
(the literal string: __main__
).
This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
pass
def some_function(*args,**kwargs):
pass
if __name__ == '__main__':
print("This only executes when %s is executed rather than imported" % __file__)
Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.
It's important to understand that all of the code above the if __name__
line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print
statement before the if __name__
line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).
I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.
Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"
to isolate a block of code which calls a suite of unit tests that apply to this module.
(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).
Summary: if __name__ == '__main__':
has two primary use cases:
It's fairly common to def main(*args)
and have if __name__ == '__main__':
simply call main(*sys.argv[1:])
if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()
and calling test_module()
in your if __name__ == '__main__:'
suite.
if __file__ == $0
).Try this:
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
</SCRIPT>
</head>
<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form>
This will work only on IE
For me, three steps solved this problem on windows 10:
I downloaded MySQL server community edition zip and extracted it in the D drive. After that I went to bin
folder and did cmd
on that folder. I followed the below steps and all works:
D:\tools\mysql-8.0.17-winx64\bin>mysqld -install
Service successfully installed.
D:\tools\mysql-8.0.17-winx64\bin>mysqld --initialize
D:\tools\mysql-8.0.17-winx64\bin>net start mysql
The MySQL service is starting...
The MySQL service was started successfully.
We have set compatibility mode for IE11 to resolve an issue: Settings>Compatibility View Settings>Add your site name or Check "Display intranet sites in Compatibility View" if your portal is in the intranet.
IE version 11.0.9600.16521
Worked for us, hope this helps someone.
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
In Javascript you can do the following:
Object.keys(ahash)[0];
Your should really use the INFORMATION_SCHEMA
views in your database:
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You can then filter that by table schema and/or table type, e.g.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
You could tell wget to not download the contents in a couple of different ways:
wget --spider http://www.example.com/cronit.php
which will just perform a HEAD request but probably do what you want
wget -O /dev/null http://www.example.com/cronit.php
which will save the output to /dev/null (a black hole)
You might want to look at wget's -q switch too which prevents it from creating output
I think that the best option would probably be:
wget -q --spider http://www.example.com/cronit.php
that's unless you have some special logic checking the HTTP method used to request the page
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
Yes, you can easily make ls
output one filename per line:
ls -a | cat
Explanation: The command ls
senses if the output is to a terminal or to a file or pipe and adjusts accordingly.
So, if you pipe ls -a
to python it should work without any special measures.
Date
is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
It has no concept of format.
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
Outputs...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
You should be making use of the ThreeTen Backport
For example...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
Outputs...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
None of the formatting has changed the underlying Date
value. This is the purpose of the DateFormatter
s
Updated with additional example
Just in case the first example didn't make sense...
This example uses two formatters to format the same date. I then use these same formatters to parse the String
values back to Date
s. The resulting parse does not alter the way Date
reports it's value.
Date#toString
is just a dump of it's contents. You can't change this, but you can format the Date
object any way you like
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat
to make sure you're not using the wrong patterns ;)
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
But I have declared that var in the top of the other files.
That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const
.
Instead, use var
, use only one declaration in your main file, or only assign to window.APP
exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.
This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory
Open "C:\satheesh\myfile\Hello.txt" For Input As #1
do until EOF(1)
Input #1, ReadedData
loop**