This can happen if you call
.SingleOrDefault()
on an IEnumerable with 2 or more elements.
PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).
If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.
openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts
The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.
You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:
openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
yes, it's really just a matter of showing/hiding an animated gif.
For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:
$(document).on('mouseenter','[rel=tooltip]', function(){
$(this).tooltip('show');
});
$(document).on('mouseleave','[rel=tooltip]', function(){
$(this).tooltip('hide');
});
There's a workaround for IE - use inline SVG and set pointer-events="none" in SVG. See my answer in How to make Internet Explorer emulate pointer-events:none?
For FC22 server
cd /etc/httpd/conf edit httpd.conf [enter]
Change: Listen 80 to: Listen whatevernumber
Save the file
systemctl restart httpd.service [enter] if required, open whatevernumber in your router / firewall
From site PostgreSQL, of date 02/04/2016 (https://jdbc.postgresql.org/download.html):
"This is the current version of the driver. Unless you have unusual requirements (running old applications or JVMs), this is the driver you should be using. It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM. It contains support for SSL and the javax.sql package. If you are using the 1.6 then you should use the JDBC4 version. If you are using 1.7 then you should use the JDBC41 version. If you are using 1.8 then you should use the JDBC42 versionIf you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver, which will by necessity not be current"
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9002)
>>> random.randint(1, 10)
3
You try this.
Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).
Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.
JustinStolle's answer in a different way. A few notes:
print
statement may truncate the string to 4000 characters, but my test string for example was 9520 characters in length.[tr/th]
indicates hierarchy, e.g., <tr><th>...</th></tr>
.[@name]
adds fields as XML attributes.null
in between fields prevents that.declare @body nvarchar(max)
select @body = cast((
select N'2' [@cellpadding], N'2' [@cellspacing], N'1' [@border],
N'Database Table' [tr/th], null [tr/td],
N'Entity Count' [tr/th], null [tr/td],
N'Total Rows' [tr/th], null,
(select object_name( object_id ) [td], null,
count( distinct name ) [td], null,
count( * ) [td], null
from sys.columns
group by object_name( object_id )
for xml path('tr'), type)
for xml path('table'), type
) as nvarchar(max))
print @body -- only shows up to 4000 characters depending
Below code worked for me without looking for any other Python libraries.
def count_repeated_letter(string1):
list1=[]
for letter in string1:
if string1.count(letter)>=2:
if letter not in list1:
list1.append(letter)
for item in list1:
if item!= " ":
print(item,string1.count(item))
count_repeated_letter('letter has 1 e and 2 e and 1 t and two t')
Output:
e 4
t 5
a 4
1 2
n 3
d 3
This is how I would do it, in order to get in the var4 restriction:
dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )
Rgds, Rainer
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
So .. quickest way is rename site config names ending in ".conf"
mv /etc/apache2/sites-available/mysite /etc/apache2/sites-available/mysite.conf
a2ensite mysite.conf
other notes on previous comments:
IncludeOptional wasn't introduced until apache 2.36 - making change above followed by restart on 2.2 will leave your server down!
also, version 2.2 a2ensite can't be hacked as described
as well, since your sites-available file is actually a configuration file, it should be named that way anyway..
In general do not restart services (webservers are one type of service):
Servers can run for many years - live update, reload config, etc.
The cloud doesn't mean you have to restart to load a configuration file.
When changing configuration of a service use "reload" not "restart".
restart stops the service then starts service - if there is a any problem in your change to the config, the service will not restart.
reload will give an error but the service never shuts down giving you a chance to fix the config error which could only be bad syntax.
debian or ubunto [service-name for this thread is apache2]
service {service-name} {start} {stop} {reload} ..
other os's left as an excersize for the reader.
to make the difference between a refresh and a closed tab or navigator, here is how I fixed it :
<script>_x000D_
function endSession() {_x000D_
// Browser or Broswer tab is closed_x000D_
// Write code here_x000D_
}_x000D_
</script>_x000D_
_x000D_
<body onpagehide="endSession();">_x000D_
_x000D_
</body>
_x000D_
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)
I have a small utility function to convert all possible values into Boolean.
private boolean convertToBoolean(String value) {
boolean returnValue = false;
if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) ||
"true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value))
returnValue = true;
return returnValue;
}
Also ran into this error message, but the root cause was of a different flavor from those referenced in the other answers here.
Generic answer: Make sure that once hibernate loads an entity, no code changes the primary key value in that object in any way. When hibernate flushes all changes back to the database, it throws this exception because the primary key changed. If you don't do it explicitly, look for places where this may happen unintentionally, perhaps on related entities that only have LAZY loading configured.
In my case, I am using a mapping framework (MapStruct) to update an entity. In the process, also other referenced entities were being updates as mapping frameworks tend to do that by default. I was later replacing the original entity with new one (in DB terms, changed the value of the foreign key to reference a different row in the related table), the primary key of the previously-referenced entity was already updated, and hibernate attempted to persist this update on flush.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
String header = dataGridView1.Columns[i].HeaderText;
//String cellText = row.Cells[i].Text;
DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
int colWidth = column.Width; // store columns width after auto resize
colWidth += 50; // add 30 pixels to what 'colWidth' already is
this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
}
}
You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.
In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).
In HTML5 there is the global hidden
attribute:
When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the
hidden
attribute specified.
Example (using the small
element here, because it’s an "attribution"):
<small hidden>Thanks to John Doe for this idea.</small>
As a fallback (for user-agents that don’t know the hidden
attribute), you can specify in your CSS:
[hidden] {display:none;}
An general element for plain text could be the script
element used as "data block":
<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>
Alternatively, you could also use data-*
attributes on existing elements (resp. on new div
elements if you want to group some elements for the attribution):
<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>
You could try this:
$(".edgetoedge").children().removeClass("highlight");
iPhone OS 3.0 and later supports the cornerRadius
property on the CALayer
class. Every view has a CALayer
instance that you can manipulate. This means you can get rounded corners in one line:
view.layer.cornerRadius = 8;
You will need to #import <QuartzCore/QuartzCore.h>
and link to the QuartzCore framework to get access to CALayer's headers and properties.
One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:
UIView
subclass and name it something like RoundRectView
.RoundRectView
's drawRect:
method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.UILabel
instance and make it a subview of the RoundRectView.label.frame = CGRectInset(roundRectView.bounds, 8, 8);
)You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.
Make sure you take into account that adding this tag,
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
may only allow compatibility with the latest versions. It all depends on your libraries
For my scheduler, I am using it to fire at 6 am every day and my cron notation is:
0 0 6 * * *
If you want 1:01:am then set it to
0 1 1 * * *
Complete code for the scheduler
@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
//complete scheduled work
}
** VERY IMPORTANT
To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):
@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
//complete scheduled work
}
You can find the complete time zone values from here.
Note: My Spring framework version is: 4.0.7.RELEASE
In Bootstrap 4 there is the utility class border-right
which you can use.
So for example you can do:
<div class="row">
<div class="col-6 border-right"></div>
<div class="col-6"></div>
</div>
I'd think some datbases can import data from CSV (comma separated values) files, wich you can export from exel. Or at least it's quite easy to use a csv parser (find one for your language, don't try to create one yourself - it's harder than it looks) to import it to the database.
I'm not familiar with MS SQL but it wouldn't suprise me if it does support it directly.
In any case I think the requrement must be that the structure in the Exel sheet and the database table is similar.
This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..
Both should be same ..Java version
mismatched ..Check it
Some improved version with max lvl to go down in directory and option to exclude folders:
using System;
using System.IO;
class MainClass {
public static void Main (string[] args) {
var dir = @"C:\directory\to\print";
PrintDirectoryTree(dir, 2, new string[] {"folder3"});
}
public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
{
excludedFolders = excludedFolders ?? new string[0];
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator+Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(directory))
{
Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
{
PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+" ");
}
}
}
}
input directory:
-folder1
file1.txt
-folder2
file2.txt
-folder5
file6.txt
-folder3
file3.txt
-folder4
file4.txt
file5.txt
output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):
-folder1
file1.txt
-folder2
file2.txt
-folder5
-folder3
-folder4
file4.txt
file5.txt
function filesModelDirective(){
return {
controller: function($parse, $element, $attrs, $scope){
var exp = $parse($attrs.filesModel);
$element.on('change', function(){
exp.assign($scope, this.files[0]);
$scope.$apply();
});
}
};
}
app.directive('filesModel', filesModelDirective);
I made a simple wrapper for the Fullscreen API, called screenfull.js, to smooth out the prefix mess and fix some inconsistencies in the different implementations. Check out the demo to see how the Fullscreen API works.
Recommended reading:
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
From your question it seems like you are using C99, as you have used %lf
for double.
To achieve the desired output replace:
sprintf(aa, "%lf", a);
with
sprintf(aa, "%0.7f", a);
The general syntax "%A.B"
means to use B digits after decimal point. The meaning of the A
is more complicated, but can be read about here.
Simply add your NextActivity
in the Manifest.XML
file
<activity
android:name="com.example.sms1.NextActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
Assuming we can use some ES6 syntax like the spread operator, we'll want to do something as many times as the sum of all numbers in the collection.
In this case if times is equal to [1,2,3]
, the total number of times will be 6, i.e. 1+2+3.
/**
* @param {number[]} times
* @param {cb} function
*/
function doTimes(times, cb) {
// Get the sum of all the times
const totalTimes = times.reduce((acc, time) => acc + time);
// Call the callback as many times as the sum
[...Array(totalTimes)].map(cb);
}
doTimes([1,2,3], () => console.log('something'));
// => Prints 'something' 6 times
This post should be helpful if the logic behind constructing and spreading an array isn't apparent.
For people like me who get confused while using cmake
, the FindCUDA.cmake
script overrides some of the stuff from nvcc.profile
. You can specify the nvcc
host compiler by setting CUDA_HOST_COMPILER
as per http://public.kitware.com/Bug/view.php?id=13674.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));
See this MSDN page.
Hope that helps out!
You can use guava's Sets.newSetFromMap(map)
to get one. Java 6 also has that method in java.util.Collections
This isn't Perl; you don't want to force-fit multiple lines worth of code onto a single line. Write a function, then calling the function takes one line of code.
def read_file(fn):
"""
>>> import os
>>> fn = "/tmp/testfile.%i" % os.getpid()
>>> open(fn, "w+").write("testing")
>>> read_file(fn)
'testing'
>>> os.unlink(fn)
>>> read_file("/nonexistant")
Traceback (most recent call last):
...
IOError: [Errno 2] No such file or directory: '/nonexistant'
"""
with open(fn) as f:
return f.read()
if __name__ == "__main__":
import doctest
doctest.testmod()
Up to Xcode 5 the preprocessor directive #pragma mark
existed.
From Xcode 6 on, you have to use // MARK:
These preprocessor features allow to bring some structure to the function drop down box of the source code editor.
some examples :
// MARK:
-> will be preceded by a horizontal divider
// MARK: your text goes here
-> puts 'your text goes here' in bold in the drop down list
// MARK: - your text goes here
-> puts 'your text goes here' in bold in the drop down list, preceded by a horizontal divider
update : added screenshot 'cause some people still seem to have issues with this :
This is an easy way to get a successful response from the server like PHP echo otherwise an error message.
BufferedReader br = null;
if (conn.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
}
This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
typedef double (*pf)(double x); /*this defines a type pf */
double f1(double x) { return(x+x);}
double f2(double x) { return(x*x);}
pf pa[] = {f1, f2};
main()
{
pf p;
p = pa[0];
printf("%f\n", p(3.0));
p = pa[1];
printf("%f\n", p(3.0));
}
One liner which works for all Android versions:
adb shell 'cat `pm path com.example.name | cut -d':' -f2`' > app.apk
more.exe
exists on Windows, ports of less
are easily found (and the PowerShell Community Extensions, PSCX, includes one).
PowerShell doesn't really provide any alternative to separate programs for either, but for structured data Out-Grid
can be helpful.
Head
and Tail
can both be emulated with Select-Object
using the -First
and -Last
parameters respectively.
Sed
functions are all available but structured rather differently. The filtering options are available in Where-Object
(or via Foreach-Object
and some state for ranges). Other, transforming, operations can be done with Select-Object
and Foreach-Object
.
However as PowerShell passes (.NET) objects – with all their typed structure, eg. dates remain DateTime
instances – rather than just strings, which each command needs to parse itself, much of sed
and other such programs are redundant.
Task.WaitAll
blocks the current thread until everything has completed.
Task.WhenAll
returns a task which represents the action of waiting until everything has completed.
That means that from an async method, you can use:
await Task.WhenAll(tasks);
... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.
Although the answers above seems correct, just a simple explanation to give you an idea of how it works.
Suppose that your column is set to be DECIMAL(13,4)
. This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.
So, in summary, for that column you would have a max value of: 999999999.9999
Performance Analysis For loops performs faster than map or foreach as number of elements in a array increases.
let array = [];
for (var i = 0; i < 20000000; i++) {
array.push(i)
}
console.time('map');
array.map(num => {
return num * 4;
});
console.timeEnd('map');
console.time('forEach');
array.forEach((num, index) => {
return array[index] = num * 4;
});
console.timeEnd('forEach');
console.time('for');
for (i = 0; i < array.length; i++) {
array[i] = array[i] * 2;
}
console.timeEnd('for');
I use Windows 7 Professional 64-bit and have both the 32-bit and 64-bit Java 7u9 jre's installed. Chrome refused to work until I deleted the following registry key.
HKEY_LOCAL_MACHINE/Software/MozillaPlugins/@java.com/DTPlugin,version=10.9.2
Then I refreshed Chrome and the Applet loaded with a Warning that the plugin was out of date. I seleted "Run this time" and everything worked as expected.
Code Runner Extension will only let you "run" java files.
To truly debug 'Java' files follow the quick one-time setup:
.vscode
in the same folder..vscode
folder: tasks.json
and launch.json
tasks.json
:{ "version": "2.0.0", "type": "shell", "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "isBackground": true, "tasks": [ { "taskName": "build", "args": ["-g", "${file}"], "command": "javac" } ] }
launch.json
:{ "version": "0.2.0", "configurations": [ { "name": "Debug Java", "type": "java", "request": "launch", "externalConsole": true, //user input dosen't work if set it to false :( "stopOnEntry": true, "preLaunchTask": "build", // Runs the task created above before running this configuration "jdkPath": "${env:JAVA_HOME}/bin", // You need to set JAVA_HOME enviroment variable "cwd": "${workspaceRoot}", "startupClass": "${workspaceRoot}${file}", "sourcePath": ["${workspaceRoot}"], // Indicates where your source (.java) files are "classpath": ["${workspaceRoot}"], // Indicates the location of your .class files "options": [], // Additional options to pass to the java executable "args": [] // Command line arguments to pass to the startup class } ], "compounds": [] }
You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).
Tip: *To hide .class files in the side explorer of VS code, open settings
of VS code and paste the below config:
"files.exclude": {
"*.class": true
}
The bit rate is a measure of the number of bits that are transmitted per unit of time.
The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.
Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.
The binary equivalent is 01010010.
So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).
Another option is:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
If you use the command
time /T
that will print the time. (without the /T, it will try to set the time)
date /T
is similar for the date.
If cmd's Command Extensions are enabled (they are enabled by default, but in this question they appear to be disabled), then the environment variables %DATE%
and %TIME%
will expand to the current date and time each time they are expanded. The format used is the same as the DATE
and TIME
commands.
To see the other dynamic environment variables that exist when Command Extensions are enabled, run set /?
.
The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:
nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)
readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.
retain vs. copy vs. assign
using $cfg['Servers'][$i]['auth_type'] = 'config';
is insecure i think.
using cookies with $cfg['Servers'][$i]['auth_type'] = 'cookie';
is better i think.
I also added:
$cfg['LoginCookieRecall'] = true;
$cfg['LoginCookieValidity'] = 100440;
$cfg['LoginCookieStore'] = 0; //Define how long login cookie should be stored in browser. Default 0 means that it will be kept for existing session. This is recommended for not trusted environments.
$cfg['LoginCookieDeleteAll'] = true; //If enabled (default), logout deletes cookies for all servers, otherwise only for current one. Setting this to false makes it easy to forget to log out from other server, when you are using more of them.
I added this in phi.ini
session.gc_maxlifetime=150000
You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.
It would be nice if you could do the following:
SELECT DATETIME(col, 'PDT')
...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.
Doesn't deal with daylight saving rules, though...
If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().
If you want to close all windows and terminate the application use System.exit()
Do not rely on the windows path variable because it gets changed in nearly every update. E.g. a chrome (32bit on a 64 bit machine) java update replaces the systemwide 64 bit JVM by a 32 bit JVM. Note also that this entry has to be the last one in the eclipse.ini, otherwise it does not work,And - as otherwise stated - the JAVA_HOME variable is NOT evaluated by eclipse.exe.
even if your has JAVA_HOME and Path configured valid,their may has this problem,so the most simple way to do is open your eclipse.ini in your eclipse installtion folder
-vm
C:\Program Files\Java\jdk1.7.0_71\bin\javaw.exe
replace C:\Program Files\Java\jdk1.7.0_71\bin\javaw.exe with your jdk or jre `s path
Yes, this way:
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))
print(r, g, b)
(65, 100, 137)
The reason you were getting a single value before with pix[1, 1]
is because GIF pixels refer to one of the 256 values in the GIF color palette.
See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert()
function.
By the way, your code would work just fine for .jpg
images.
You can use os.listdir() to get the files in the source directory, os.path.isfile() to see if they are regular files (including symbolic links on *nix systems), and shutil.copy to do the copying.
The following code copies only the regular files from the source directory into the destination directory (I'm assuming you don't want any sub-directories copied).
import os
import shutil
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, dest)
It's good practice to use a StringBuilder
when concatenating a lot of strings and you can then use the Remove method to get rid of the final character.
StringBuilder paramBuilder = new StringBuilder();
foreach (var item in itemsToAdd)
{
paramBuilder.AppendFormat(("productID={0}&", item.prodID.ToString());
}
if (paramBuilder.Length > 1)
paramBuilder.Remove(paramBuilder.Length-1, 1);
string s = paramBuilder.ToString();
"Easiest way is to use the built-in feature of SQL Management Studio" but... I have resolved it with a function and a couple of procedures. For example, to obtain the create table for a table named 'table_name', you have to execute just the procedure called sp_ppinScriptTabla:
Exec sp_ppinScriptTabla 'table_name'
Here is the tsql script code:
Use Master
GO
Create Function sp_ppinTipoLongitud
(
@xtype int,
@length int,
@isnullable int
)
Returns Varchar(512)
As
Begin
-- Función que a partir de un tipo de datos y una logitud, devuelve el texto del tipo.
-- Por ejemplo: para xtype=varchar y length=10 devolverá "varchar(10)"
Declare @ret varchar(512)
Set @ret = ''
Select @ret = t.name +
Case When name in ('varchar', 'nvarchar', 'char', 'nchar') Then '(' + Convert(varchar, @length) + ')' Else '' End + ' ' +
Case @isnullable When 1 Then 'NULL' Else 'NOT NULL' End
From systypes t
Where t.xtype = @xtype
Return @ret
End
GO
Create Procedure sp_ppinScriptLlavesForaneas
(
@vchTabla sysname,
@vchResultado varchar(8000) output
)
AS
Begin
DECLARE @tmpFK table(
TablaF sysname,
TablaR sysname,
ColF sysname,
ColR sysname,
FKName sysname)
-- obtengo las llaves foraneas en @vchForeign
Declare @vchForeign varchar(8000), @FKName sysname, @vchColumnasF varchar(4000), @vchColumnasR varchar(4000), @ColF sysname, @ColR sysname
Declare @vchTemp varchar(1000), @TablaR sysname
Insert into @tmpFK
Select TablaF.name AS TablaF, TablaR.name AS TablaR, ColF.name AS ColF, ColR.name AS ColR, ofk.name AS FKName
From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR,
syscolumns ColF, syscolumns ColR
Where TablaF.name = @vchTabla
And ofk.id = fk.constid
And TablaF.id = fk.fkeyid
And TablaR.id = fk.rkeyid
And ColF.id = TablaF.id And ColF.colid = fk.fkey
And ColR.id = TablaR.id And ColR.colid = fk.rkey
order by FKName
Set @vchForeign = ''
While Exists ( Select * From @tmpFK )
Begin
Select Top 1 @FKName = FKName From @tmpFK
Set @vchColumnasF = ''
Set @vchColumnasR = ''
While Exists ( Select * From @tmpFK Where FKName = @FKName )
Begin
Select Top 1 @ColF = ColF, @ColR = ColR, @TablaR = TablaR From @tmpFK Where FKName = @FKName
Delete From @tmpFK Where ColF = @ColF And ColR = @ColR And TablaR = @TablaR And FKName = @FKName
Set @vchColumnasF = @vchColumnasF + @ColF + ', '
Set @vchColumnasR = @vchColumnasR + @ColR + ', '
End
Set @vchColumnasF = LEFT(@vchColumnasF, LEN(@vchColumnasF) - 1)
Set @vchColumnasR = LEFT(@vchColumnasR, LEN(@vchColumnasR) - 1)
Set @vchTemp = 'Constraint ' + @FKName + ' Foreign Key (' + @vchColumnasF + ') '
Set @vchTemp = @vchTemp + 'References ' + @TablaR + ' (' + @vchColumnasR + ')'
Set @vchForeign = @vchForeign + char(9) + @vchTemp + ',' + char(13)
End
Select @vchResultado = Case When Len(@vchForeign) >=2 Then Left(@vchForeign, Len(@vchForeign) - 2) Else @vchForeign End
End
GO
Create Procedure sp_ppinScriptTabla
(
@vchTabla sysname
)
AS
Set nocount on
-- Obtengo las foreign keys
Declare @foreign varchar(8000)
Exec sp_ppinScriptLlavesForaneas @vchTabla, @foreign output
-- SELECT que devuelve el script de Create Table de la tabla
Select 'Create ' +
Case o.xtype When 'U' Then 'Table' When 'P' Then 'Procedure' Else '??' End + ' ' +
@vchTabla + char(13) + '('
From sysobjects o
Where o.name = @vchTabla
Union all
-- Campos + identitys + DEFAULTS
select char(9) + c.name + ' ' + -- Nombre
dbo.sp_ppinTipoLongitud(t.xtype, c.length, c.isnullable) + -- Tipo(longitud)
Case When c.colstat & 1 = 1 -- Identity (si aplica)
Then ' Identity(' + convert(varchar, ident_seed(@vchTabla)) + ',' + Convert(varchar, ident_incr(@vchTabla)) + ')'
Else ''
End +
Case When not od.name is null -- Defaults (si aplica)
Then ' Constraint ' + od.name + ' Default ' + replace(replace(cd.text, '((', '('), '))', ')')
Else ''
End + ', '
from sysobjects o, syscolumns c
LEFT OUTER JOIN sysobjects od On od.id = c.cdefault LEFT OUTER join syscomments cd On cd.id = od.id,
systypes t
where o.id = object_id(@vchTabla)
and o.id = c.id
and c.xtype = t.xtype
Union all
-- Primary Keys y Unique keys
select char(9) + 'Constraint ' + o.name + ' ' +
Case o.xtype When 'PK' Then 'Primary Key' Else 'Unique' End + ' ' +
dbo.sp_ppinCamposIndice (db_name(), @vchTabla, i.indid) + ', '
from sysobjects o, sysindexes i
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('PK','UQ')
and i.id = o.parent_obj
and o.name = i.name
Union all
-- Check constraints
select char(9) + 'Constraint ' + o.name + ' Check ' + c.text + ', '
from sysobjects o, syscomments c
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('C')
and o.id = c.id
Union all
-- Foreign keys
Select @foreign
Union all
Select ')'
Set nocount off
GO
If you can add an extra couple of divs so your html looks like this:
<div id="wrapper">
<div id="first" class="row">
<div class="cell"></div>
</div>
<div id="second" class="row">
<div class="cell"></div>
</div>
</div>
You can make use of the display:table
properties:
#wrapper
{
width:300px;
height:100%;
display:table;
}
.row
{
display:table-row;
}
.cell
{
display:table-cell;
}
#first .cell
{
height:200px;
background-color:#F5DEB3;
}
#second .cell
{
background-color:#9ACD32;
}
This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.
Question originally posted 4 years ago.
Use the spring initializer to generate a demo app
Extract the zip archive locally
#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]
Note
docker build -t demo .
$ docker run --rm -it demo:latest
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-02-22 17:18:57.835 INFO 1 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837 INFO 1 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294 INFO 1 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.711 seconds (JVM running for 1.035)
Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.
This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.
This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.
The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.
FROM maven:3.5-jdk-8 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app
RUN mvn -f /usr/src/app/pom.xml clean package
FROM gcr.io/distroless/java
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]
Note:
I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)
https://github.com/GoogleContainerTools/jib
The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.
Try using the new official images, there's one for Maven
https://registry.hub.docker.com/_/maven/
The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.
The following command runs your Maven build inside a container:
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
maven:3.2-jdk-7 \
mvn clean install
Notes:
Run the Nexus container
docker run -d -p 8081:8081 --name nexus sonatype/nexus
Create a "settings.xml" file:
<settings>
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://nexus:8081/content/groups/public/</url>
</mirror>
</mirrors>
</settings>
Now run Maven linking to the nexus container, so that dependencies will be cached
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
--link nexus:nexus \
maven:3.2-jdk-7 \
mvn -s settings.xml clean install
Notes:
With python >= 3.5
you can use mock_object.assert_not_called()
.
Static Object: We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.
Let us try the following example to understand the concept of static data members:
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Total objects: 2
Static Function Members: By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
A static member function can only access static data member, other static member functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.
Let us try the following example to understand the concept of static function members:
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
{
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
Here is a good article from Microsoft http://www.iis.net/learn/troubleshoot/security-issues/troubleshooting-forms-authentication that covers various cases and scenarios.
I've recently found that blanks in the name of the redirect file will cause the "ambiguous redirect" message.
For example if you redirect to application$(date +%Y%m%d%k%M%S).log
and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log
it would succeed. This is because the %k
format yields ' 9'
for 9AM where %H
yields '09'
for 9AM.
echo $(date +%Y%m%d%k%M%S)
gives 20140626 95138
echo $(date +%Y%m%d%H%M%S)
gives 20140626095138
The erroneous date might give something like:
echo "a" > myapp20140626 95138.log
where the following is what would be desired:
echo "a" > myapp20140626095138.log
This can be caused if the client is in a different domain than the server.
I encountered this when testing one of my applications from my PC(client) to my (cloud) testing server and the simplest solution i could think of was setting up a vpn.
As pointed out by an answer above, you can use javax.ws.rs.core.MediaType
which has the required constants.
I also wanted to share a really cool and handy link which I found that gives a reference to all the Javax constants in one place - https://docs.oracle.com/javaee/7/api/constant-values.html.
I found an easy and nice solution:
char*string_acquire(char*s,int size,FILE*stream){
int i;
fgets(s,size,stream);
i=strlen(s)-1;
if(s[i]!='\n') while(getchar()!='\n');
if(s[i]=='\n') s[i]='\0';
return s;
}
it's based on fgets but free from '\n' and stdin extra characters (to replace fflush(stdin) that doesn't works on all OS, useful if you have to acquire strings after this).
The most likely explanations for that error are:
CreateProcess
requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute
rather than CreateProcess
.Reading down to the bottom of the code, I can see that the problem is number 1.
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
This can now be achieve through the css method :focus-within
as examplified in this post: http://www.scottohara.me/blog/2017/05/14/focus-within.html
/*_x000D_
A normal (though ugly) focus_x000D_
pseudo-class. Any element that_x000D_
can receive focus within the_x000D_
.my-element parent will receive_x000D_
a yellow background._x000D_
*/_x000D_
.my-element *:focus {_x000D_
background: yellow !important;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
/*_x000D_
The :focus-within pseudo-class_x000D_
will NOT style the elements within_x000D_
the .my-element selector, like the_x000D_
normal :focus above, but will_x000D_
style the .my-element container_x000D_
when its focusable children_x000D_
receive focus._x000D_
*/_x000D_
.my-element:focus-within {_x000D_
outline: 3px solid #333;_x000D_
}
_x000D_
<div class="my-element">_x000D_
<p>A paragraph</p>_x000D_
<p>_x000D_
<a href="http://scottohara.me">_x000D_
My Website_x000D_
</a>_x000D_
</p>_x000D_
_x000D_
<label for="wut_email">_x000D_
Your email:_x000D_
</label>_x000D_
<input type="email" id="wut_email" />_x000D_
</div>
_x000D_
If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Use this, from here:
function insertAtCaret(areaId, text) {_x000D_
var txtarea = document.getElementById(areaId);_x000D_
if (!txtarea) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var scrollPos = txtarea.scrollTop;_x000D_
var strPos = 0;_x000D_
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?_x000D_
"ff" : (document.selection ? "ie" : false));_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var range = document.selection.createRange();_x000D_
range.moveStart('character', -txtarea.value.length);_x000D_
strPos = range.text.length;_x000D_
} else if (br == "ff") {_x000D_
strPos = txtarea.selectionStart;_x000D_
}_x000D_
_x000D_
var front = (txtarea.value).substring(0, strPos);_x000D_
var back = (txtarea.value).substring(strPos, txtarea.value.length);_x000D_
txtarea.value = front + text + back;_x000D_
strPos = strPos + text.length;_x000D_
if (br == "ie") {_x000D_
txtarea.focus();_x000D_
var ieRange = document.selection.createRange();_x000D_
ieRange.moveStart('character', -txtarea.value.length);_x000D_
ieRange.moveStart('character', strPos);_x000D_
ieRange.moveEnd('character', 0);_x000D_
ieRange.select();_x000D_
} else if (br == "ff") {_x000D_
txtarea.selectionStart = strPos;_x000D_
txtarea.selectionEnd = strPos;_x000D_
txtarea.focus();_x000D_
}_x000D_
_x000D_
txtarea.scrollTop = scrollPos;_x000D_
}
_x000D_
<textarea id="textareaid"></textarea>_x000D_
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
_x000D_
FWIW with Ansible 2.2 one can use include_role:
playbook test.yml
:
- name: test
hosts:
- 127.0.0.1
connection: local
tasks:
- include_role:
name: test
tasks_from: other
then in roles/test/tasks/other.yml
:
- name: say something else
shell: echo "I'm the other guy"
And invoke the playbook with: ansible-playbook test.yml
to get:
TASK [test : say something else] *************
changed: [127.0.0.1]
Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use min/max-width/height
on a larger area and then scale that area back into the original dimensions.
.container {_x000D_
width: 800px;_x000D_
height: 300px;_x000D_
border: 1px solid black;_x000D_
overflow:hidden;_x000D_
position:relative;_x000D_
}_x000D_
.container.contain img {_x000D_
position: absolute;_x000D_
left:-10000%; right: -10000%; _x000D_
top: -10000%; bottom: -10000%;_x000D_
margin: auto auto;_x000D_
max-width: 10%;_x000D_
max-height: 10%;_x000D_
-webkit-transform:scale(10);_x000D_
transform: scale(10);_x000D_
}_x000D_
.container.cover img {_x000D_
position: absolute;_x000D_
left:-10000%; right: -10000%; _x000D_
top: -10000%; bottom: -10000%;_x000D_
margin: auto auto;_x000D_
min-width: 1000%;_x000D_
min-height: 1000%;_x000D_
-webkit-transform:scale(0.1);_x000D_
transform: scale(0.1);_x000D_
}
_x000D_
<h1>contain</h1>_x000D_
<div class="container contain">_x000D_
<img _x000D_
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
/>_x000D_
<!-- 366x200 -->_x000D_
</div>_x000D_
<h1>cover</h1>_x000D_
<div class="container cover">_x000D_
<img _x000D_
src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
/>_x000D_
<!-- 366x200 -->_x000D_
</div>
_x000D_
If you are using it in a table use this :-
<script type="text/javascript">
function showStuff(id, text, btn) {
document.getElementById(id).style.display = 'table-row';
// hide the lorem ipsum text
document.getElementById(text).style.display = 'none';
// hide the link
btn.style.display = 'none';
}
</script>
<td class="post">
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>
The keyword extends
can be used for interfaces and classes only.
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
It does not work the other way round - UserEvent
must be declared as interface, not a type
if you want to use extends
syntax.
And it's still impossible to use extend
with arbitrary types - for example, it does not work if Event
is a type parameter without any constraints.
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
E.g.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
Just adding this here in case someone runs into this issue within a virtualbox container running docker. I reconfigured the virtualbox network to bridged instead of nat, and the problem went away.
In command line before typing "jupyter notebook
" navigate to the desired folder.
In my case my all python files are in "D:\Python".
Then type the command "jupyter notebook" and there you have it. You have changed your working directory.
<body topmargin="0" leftmargin="0" rightmargin="0">
I'm not sure where you read this, but this is the accepted way of setting CSS styles inline is:
<body style="margin-top: 0px; margin-left: 0px; margin-right: 0px;">
And with a stylesheet:
body
{
margin-top: 0px;
margin-left: 0px;
margin-right: 0px;
}
To Validate Text Box Accept Ascii Only use this Pattern
[\x00-\x7F]+
import sys
import time
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
# \r prints a carriage return first, so `b` is printed on top of the previous line.
sys.stdout.write('\r'+b)
time.sleep(0.5)
print (a)
Note that you might have to run sys.stdout.flush()
right after sys.stdout.write('\r'+b)
depending on which console you are doing the printing to have the results printed when requested without any buffering.
If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:
$ rm -f abc.log.* # Remove them all
$ rm -f abc.log.2012* # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012
Regular expressions are more powerful than wildcards; you can feed the output of grep
to rm -f
. For example, if some of the file names start with "abc.log"
and some with "ABC.log"
, grep
lets you do a case-insensitive match:
$ rm -f $(ls | grep -i '^abc\.log\.')
This will cause problems if any of the file names contain funny characters, including spaces. Be careful.
When I do this, I run the ls | grep ...
command first and check that it produces the output I want -- especially if I'm using rm -f
:
$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)
where !!
expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f
command.
This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...)
syntax. You can use the equivalent backtick syntax:
$ rm -f `ls | grep -i '^abc\.log\.'`
The $(...)
syntax is easier to read, and if you're really ambitious it can be nested.
Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:
$ ls > list
$ vi list # Use your favorite text editor
I can then edit the list
file manually, leaving only the files I want to remove, and then:
$ rm -f $(<list)
or
$ rm -f `cat list`
(Again, this assumes none of the file names contain funny characters, particularly spaces.)
Or, when editing the list
file, I can add rm -f
to the beginning of each line and then:
$ . ./list
or
$ source ./list
Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar
to rm -f 'foo bar'
.
I am using the following code in such cases:
obj, created = Model.objects.get_or_create(id=some_id)
if not created:
resp= "It was created"
else:
resp= "OK"
obj.save()
The synchronized
keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).
This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much.
Consider this:
if (vector.isEmpty()){
vector.add(data);
}
Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.
So in effect, you have to synchronize in your application code as well.
Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).
More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.
The short answer:
A const
is a promise that you will not try to modify the value once set.
A static
variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.
C99 borrowed the use of const
from C++. On the other hand, static
has been the source of many debates (in both languages) because of its often confusing semantics.
Also, with C++0x until C++11 the use of the static
keyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).
The longer answer: More on the keywords than you wanted to know (right from the standards):
C99
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage
int i2; // external linkage, automatic duration (effectively lifetime of program)
int *p = (int []){2, 4}; // unnamed array has static storage
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // static, non-modifiable
void f(int m)
{
static int vla[ m ]; // err
float w[] = { 0.0/0.0 }; // raises an exception
/* block scope, static storage, no-linkage */
static float x = 0.0/0.0; // does not raise an exception
/* ... */
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // automatic storage, non-modifiable
}
inline void bar(void)
{
const static int x = 42; // ok
// Note: Since an inline definition is distinct from the
// corresponding external definition and from any other
// corresponding inline definitions in other translation
// units, all corresponding objects with static storage
// duration are also distinct in each of the definitions
static int y = -42; // error, inline function definition
}
// the last declaration also specifies that the argument
// corresponding to a in any call to f must be a non-null
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);
static void g(void); // internal linkage
C++
Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying static
s.
extern "C" {
static void f4(); // the name of the function f4 has
// internal linkage (not C language
// linkage) and the function’s type
// has C language linkage.
}
class S {
mutable static int i; // err
mutable static int j; // err
static int k; // ok, all instances share the same member
};
inline void bar(void)
{
const static int x = 42; // ok
static int y = -42; // ok
}
There are a few more nuances of C++'s static
that I leave out here. Have a look at a book or the standard.
Based on the doc
<div class="row">
<div class="span4 collapse-group">
<h2>Heading</h2>
<p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
$('.row .btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
});
A sspi failed in xamarin android.
I found this solution; put this code before you hit on an HTTPS link
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
For Zoom In: CTRL + SHIFT + +
For Zoom Out: `CTRL + SHIFT + -
Why choose between a traditional database and a NoSQL data store? Use both! The problem with NoSQL solutions (beyond the initial learning curve) is the lack of transactions -- you do all updates to MySQL and have MySQL populate a NoSQL data store for reads -- you then benefit from each technology's strengths. This does add more complexity, but you already have the MySQL side -- just add MongoDB, Cassandra, etc to the mix.
NoSQL datastores generally scale way better than a traditional DB for the same otherwise specs -- there is a reason why Facebook, Twitter, Google, and most start-ups are using NoSQL solutions. It's not just geeks getting high on new tech.
A decimal type can not contain formatting information. You can create another property, say FormattedProperty
of a string type that does what you want.
All these comments are great, but I'm really surprised nobody mentioned Google's Objective-C Style Guide that was published a while back. I think they have done a very thorough job.
The read_excel() function has a converters argument, where you can apply functions to input in certain columns. You can use this to keep them as strings. Documentation:
Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.
Example code:
pandas.read_excel(my_file, converters = {my_str_column: str})
This error was caused, for me, by different circumstances. A downloaded project tutorial had a default setting of [Project]>Targets>Build Settings>Architectures>Build Active Architecture Only>Release = "Yes." I wasn't intending to build a release, so the solution was to set Release (which presumably requires not just a developer profile but distribution profile) to "No."
What helped me diagnose the issue was to run mongod
and specify the /etc/mondgob.conf
config file:
mongod --config /etc/mongodb.conf
That revealed that some options in /etc/mongdb.conf were "Unrecognized". I had commented out both options under security:
and left alone only security:
on one line, which caused the service to not start. This looks like a bug.
security:
# authorization: enabled
# keyFile: /etc/ssl/mongo-keyfile
^^ error
#security:
# authorization: enabled
# keyFile: /etc/ssl/mongo-keyfile
^^ correctly commented.
make sure you really load jquery this is not jquery - it's the ui!
<script language="JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js">
</script>
This is a correct script source for jquery:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
The number of string occurrences (not lines) can be obtained using grep
with -o
option and wc
(word count):
$ echo "echo 1234 echo" | grep -o echo
echo
echo
$ echo "echo 1234 echo" | grep -o echo | wc -l
2
So the full solution for your problem would look like this:
$ grep -o "echo" FILE | wc -l
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")
You need to use the full property name for each:
background-color: #6DB3F2;
background-image: url('images/checked.png');
Or, you can use the background shorthand and specify it all in one line:
background: url('images/checked.png'), #6DB3F2;
for k, m in self.materials.items():
example:
miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
print("%s: %s" % (k, v))
Navigating to folder: %systemroot%\System32\inetsrv\config
presents a security dialog. Click continue and this may resolve the issue. This has worked on two separate Win 10/VS 2017/IIS machines.
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
I suggest you to add both panel at frame creation, then change the visible panel by calling setVisible(true/false) on both. When calling setVisible, the parent will be notified and asked to repaint itself.
If your Selenium tests run in a modern browser, an easy way to obtain the response code is to send a synchronous XMLHttpRequest
* and check the status
of the response:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://exampleurl.ex', false);
xhr.send(null);
assert(200, xhr.status);
You can use this technique with any programming language by requesting that Selenium execute the script. For example, in Java you can use JavascriptExecutor.executeScript()
to send the XMLHttpRequest
:
final String GET_RESPONSE_CODE_SCRIPT =
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', arguments[0], false);" +
"xhr.send(null);" +
"return xhr.status";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
Assert.assertEquals(200,
javascriptExecutor.executeScript(GET_RESPONSE_CODE_SCRIPT, "http://exampleurl.ex"));
* You could send an asynchronous XMLHttpRequest
instead, but you would need to wait for it to complete before continuing your test.
You can obtain the response code in Java by using URL.openConnection()
and HttpURLConnection.getResponseCode()
:
URL url = new URL("http://exampleurl.ex");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
// You may need to copy over the cookies that Selenium has in order
// to imitate the Selenium user (for example if you are testing a
// website that requires a sign-in).
Set<Cookie> cookies = webDriver.manage().getCookies();
String cookieString = "";
for (Cookie cookie : cookies) {
cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
}
httpURLConnection.addRequestProperty("Cookie", cookieString);
Assert.assertEquals(200, httpURLConnection.getResponseCode());
This method could probably be generalized to other languages as well but would need to be modified to fit the language's (or library's) API.
With the background-size property in those browsers which support this very new feature of CSS.
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
If you are using Logger.getLogger(ClassName.class)
then place your log4j.properties
file in your class path:
yourproject/javaresoures/src/log4j.properties (Put inside src folder)
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab
That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/
I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.
index.html (or .php)
/resources
/css
/fonts
/images
/js
/controllers
/directives
/filters
/services
/partials (views)
I find that good for single apps. I haven't really had a project yet where I'd need multiple.
Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:
var lastSelectedOption = null;_x000D_
_x000D_
DDChange = function(Dd) {_x000D_
//Blur after change so that clicking again without _x000D_
//losing focus re-triggers onfocus._x000D_
Dd.blur();_x000D_
_x000D_
//The rest is whatever you want in the change._x000D_
var tcs = $("span.on_change_times");_x000D_
tcs.html(+tcs.html() + 1);_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};_x000D_
_x000D_
DDFocus = function(Dd) {_x000D_
lastSelectedOption = Dd.prop("selectedIndex");_x000D_
Dd.prop("selectedIndex", -1);_x000D_
_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};_x000D_
_x000D_
//On blur, set it back to the value before they clicked _x000D_
//away without selecting an option._x000D_
//_x000D_
//This is what is typically weird for the user since they _x000D_
//might click on the dropdown to look at other options,_x000D_
//realize they didn't what to change anything, and _x000D_
//click off the dropdown._x000D_
DDBlur = function(Dd) {_x000D_
if (Dd.prop("selectedIndex") === -1)_x000D_
Dd.prop("selectedIndex", lastSelectedOption);_x000D_
_x000D_
$("span.selected_index").html(Dd.prop("selectedIndex"));_x000D_
return false;_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select id="Dd" onchange="DDChange($(this));" onfocus="DDFocus($(this));" onblur="DDBlur($(this));">_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
</select>_x000D_
<br/>_x000D_
<br/>Selected index: <span class="selected_index"></span>_x000D_
<br/>Times onchange triggered: <span class="on_change_times">0</span>
_x000D_
This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.
The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class Average {
public static void main(String [] args) {
String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");
String test2= JOptionPane.showInputDialog("Please input mark for test 2: ");
String test3= JOptionPane.showInputDialog("Please input mark for test 3: ");
int int1 = Integer.parseInt(test1);
int int2 = Integer.parseInt(test2);
int int3 = Integer.parseInt(test3);
SortedSet<Integer> set = new TreeSet<>();
set.add(int1);
set.add(int2);
set.add(int3);
Integer [] intArray = set.toArray(new Integer[3]);
JFrame frame = new JFrame();
JOptionPane.showInternalMessageDialog(frame.getContentPane(), String.format("Result %f", (intArray[1] + intArray[2]) / 2.0));
}
}
Take a look at this:
(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)
June 17th, 2008
With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.
The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.
What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.
The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.
DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)
The #notifier
div which is part of the .subscriber.networkDetection
group of subscribers then has an anonymous function bound to it, effectively acting as a listener.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page
I'm not familiar with DB2, but have you tried COALESCE?
ie:
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
I know this is old, but I recently faced the same issue and I managed to pick the element by accessing only the attribute like this: document.querySelector('[name="your-selector-name-here"]');
Just in case anyone would ever need this :)
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })
to get the page scrolled with a smooth effect.
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
top: 400,_x000D_
behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
height: 1000px;_x000D_
background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
<button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
You can do something like this:
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
var i = 10;_x000D_
var int = setInterval(function() {_x000D_
window.scrollTo(0, i);_x000D_
i += 10;_x000D_
if (i >= 200) clearInterval(int);_x000D_
}, 20);_x000D_
})
_x000D_
body {_x000D_
background: #3a2613;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
ES6 recursive approach:
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
let i = h || 0;_x000D_
if (i < 200) {_x000D_
setTimeout(() => {_x000D_
window.scrollTo(0, i);_x000D_
smoothScroll(i + 10);_x000D_
}, 10);_x000D_
}_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
background: #9a6432;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
Another working option I came across is to set android:background="@null"
In my case nodemon needed to be installed globally:
npm i nodemon -g --save
I also found that JQuery plugin that is easy to include in your Angular App (also with bower :D ) and which check all possible country codes with their respective masks : intl-tel-input
You can then use the validationScript
option in order to check the validity of the input's value.
In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :
sudo -u postgres psql -d databse -f dump.sql
Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :
sudo -u postgres psql -d databse -f dump.sql -p 5433
Generally speaking, this is the pattern I use:
function empty()
does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye (sorry for my english)
function htmlEscape(str){
return str.replace(/[&<>'"]/g,x=>'&#'+x.charCodeAt(0)+';')
}
This solution uses the numerical code of the characters, for example <
is replaced by <
.
Although its performance is slightly worse than the solution using a map, it has the advantages:
Try this "one-liner" from Delta's Blog, String To MemoryStream (C#).
MemoryStream stringInMemoryStream =
new MemoryStream(ASCIIEncoding.Default.GetBytes("Your string here"));
The string will be loaded into the MemoryStream
, and you can read from it. See Encoding.GetBytes(...), which has also been implemented for a few other encodings.
To find the name of the current user within an Oracle session, use the USER
function.
Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:
select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
and Constraint_Type = 'R' and Owner = User;
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
If you don't mind one of the div
s being a master and dictating the height for both div
s there is this:
No matter what, the div
on the right will expand or squish&overflow to match the height of the div
on the left.
Both div
s must be immediate children of a container, and have to specify their widths within it.
Relevant CSS:
.container {
background-color: gray;
display: table;
width: 70%;
position:relative;
}
.container .left{
background-color: tomato;
width: 35%;
}
.container .right{
position:absolute;
top:0px;
left:35%;
background-color: orange;
width: 65%;
height:100%;
overflow-y: auto;
}
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello"
is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello"
everywhere. The header is just a hint of what format to use when reading the .py
file.
The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload
of the body-element.
The issue is a missing or outdated version of MVC. I was running VS 2015Preview and could resolve the issue by installing the latest version of MVC via NuGet.
Just in case anyone is still coming across this one.
We do this on our Intranet
You have to use System.DirectoryServices;
Here are the guts of the code
using (DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword))
{
using (DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry))
{
//adsSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")";
try
{
SearchResult adsSearchResult = adsSearcher.FindOne();
bSucceeded = true;
strAuthenticatedBy = "Active Directory";
strError = "User has been authenticated by Active Directory.";
}
catch (Exception ex)
{
// Failed to authenticate. Most likely it is caused by unknown user
// id or bad strPassword.
strError = ex.Message;
}
finally
{
adsEntry.Close();
}
}
}
http://windows.microsoft.com/en-US/windows7/schedule-a-task
maybe that will help with windows scheduled tasks ...
VM Player runs a virtual instance, but can't create the vm. [Edit: Now it can.] Workstation allows for the creation and administration of virtual machines. If you have a second machine, you can create the vm on one and run it with the player the other machine. I bought Workstation and I use it setup testing vms that the player runs. Hope this explains it for you.
Edit: According to the FAQ:
VMware Workstation is much more advanced and comes with powerful features including snapshots, cloning, remote connections to vSphere, sharing VMs, advanced Virtual Machines settings and much more. Workstation is designed to be used by technical professionals such as developers, quality assurance engineers, systems engineers, IT administrators, technical support representatives, trainers, etc.
I have used a bit of PowerShell for script automation. While it is very nice that the environment seems to have been thought out much more than Unix shells, in practice the use of objects instead of text streams is much more clunky, and a lot of the Unix facilities that have been developed in the last 30 years are still missing.
Cygwin is still my scripting environment of choice for Windows hosts. It certainly beats the alternatives in terms of getting things done.
There doesn't seem to be justify-self
, but you can achieve similar result setting appropriate margin
to auto
¹. E. g. for flex-direction: row
(default) you should set margin-right: auto
to align the child to the left.
.container {_x000D_
height: 100px;_x000D_
border: solid 10px skyblue;_x000D_
_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
}_x000D_
.block {_x000D_
width: 50px;_x000D_
background: tomato;_x000D_
}_x000D_
.justify-start {_x000D_
margin-right: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="block justify-start"></div>_x000D_
<div class="block"></div>_x000D_
</div>
_x000D_
¹ This behaviour is defined by the Flexbox spec.
const updateKey = key => console.log(key.split(' ').join('_'));
updateKey('Hello World');
_x000D_
Echo the session object as json. I like json because I have a browser extension that nicely formats json.
session_start();
echo json_encode($_SESSION);
You can see and select which Swift version Xcode is using in:
Target -> Build Settings -> Swift Language Version:
This is available in Xcode 8.3 and Xcode 9 (haven't checked older versions)
The default restart policy is no
.
For the created containers use docker update
to update restart policy.
docker update --restart=always 0576df221c0b
0576df221c0b
is the container id.
From SQL Server 2012 this is all much easier with the CONCAT
function.
It treats NULL
as empty string
DECLARE @Column1 VARCHAR(50) = 'Foo',
@Column2 VARCHAR(50) = NULL,
@Column3 VARCHAR(50) = 'Bar';
SELECT CONCAT(@Column1,@Column2,@Column3); /*Returns FooBar*/
Here is what I came up with after reading Tony Wong's comment:
public class DebugExampleTwo extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFragment(android.R.id.content,
new DebugExampleTwoFragment(),
DebugExampleTwoFragment.FRAGMENT_TAG);
}
}
...
public abstract class BaseActivity extends Activity {
protected void addFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag) {
getSupportFragmentManager()
.beginTransaction()
.add(containerViewId, fragment, fragmentTag)
.disallowAddToBackStack()
.commit();
}
protected void replaceFragment(@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag,
@Nullable String backStackStateName) {
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragment, fragmentTag)
.addToBackStack(backStackStateName)
.commit();
}
}
...
public class DebugExampleTwoFragment extends Fragment {
public static final String FRAGMENT_TAG =
BuildConfig.APPLICATION_ID + ".DEBUG_EXAMPLE_TWO_FRAGMENT_TAG";
// ...
}
If you are using Kotlin make sure to take a look at what the Kotlin extensions by Google provide or just write your own.
The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.
GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';
This will grant all privileges to one database test_database
(in your case dbTest
) to that user on localhost.
Check what permissions that above command issued to that user by running the below command.
SHOW GRANTS FOR 'user'@'localhost'
Just in case, if you want to limit the user access to only one single table
GRANT ALL ON mydb.table_name TO 'someuser'@'host';
Why can't it just use AND
in the ON
clause? For example:
SELECT *
FROM flights
INNER JOIN airports
ON ((airports.code = flights.fairport)
AND (airports.code = flights.tairport))
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId
.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
To roll back all migrations up to a particular version (e.g. 20181002222222
), use:
rake db:migrate VERSION=20181002222222
(Note that this uses db:migrate
-- not db:migrate:down
as in other answers to this question.)
Assuming the specified migration version is older than the current version, this will roll back all migrations up to, but not including, the specified version.
For example, if rake db:migrate:status
initially displays:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
up 20181003171932 Some migration description
up 20181004211151 Some migration description
up 20181005151403 Some migration description
Running:
rake db:migrate VERSION=20181002222222
Will result in:
(... some older migrations ...)
up 20181001002039 Some migration description
up 20181002222222 Some migration description
down 20181003171932 Some migration description
down 20181004211151 Some migration description
down 20181005151403 Some migration description
Reference: https://makandracards.com/makandra/845-migrate-or-revert-only-some-migrations
I was using some buttons with some events, converted image file coming from server. Loading normal data wasn't working for me, converting into Base64 working just fine.
String unencodedHtml ="<html><body>'%28' is the code for '('</body></html>";
tring encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");
Find details on WebView
Kill the process that is listening to the port in question. I believe netstat shows you process ids.
Try this code it works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
MsgBox(CustomeDate.ToString)
con.Open()
dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)
ds = New System.Data.DataSet
dadap.Fill(ds)
Dgview.DataSource = ds.Tables(0)
con.Close()
Note : if u use dd
for date representation it will return nothing while selecting 1 to 9 so use d
for selection
'Date time format
'MMM Three-letter month.
'ddd Three-letter day of the week.
'd Day of the month.
'HH Two-digit hours on 24-hour scale.
'mm Two-digit minutes.
'yyyy Four-digit year.
The documentation contains a full list of the date formats.
my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list.sort(lambda x,y : cmp(x['name'], y['name']))
my_list
will now be what you want.
Or better:
Since Python 2.4, there's a key
argument is both more efficient and neater:
my_list = sorted(my_list, key=lambda k: k['name'])
...the lambda is, IMO, easier to understand than operator.itemgetter
, but your mileage may vary.
According to the documentation, in Sublime 2, the data directory should be on these locations:
This information is available here: http://docs.sublimetext.info/en/sublime-text-2/basic_concepts.html#the-data-directory
For Sublime 3, the locations are the following:
This information is available here:http://docs.sublimetext.info/en/sublime-text-3/basic_concepts.html#the-data-directory
Run it through a fairly simple regex: [^a-zA-Z]
And then check it's length separately:
if(string.Length > 7)
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
jQuery's $.now() is an alias of new Date().getTime(), an internal Javascript function.
http://api.jquery.com/jquery.now/
This returns the number of seconds elapsed since 1970, commonly referred to (not necessarily correctly) as Unix Time, Epoch or Timestamp, depending on the circles you fall in. It can be really handy for calculating the difference between dates/times using simple maths. It doesn't have any TimeZone information and is always UTC.
http://en.wikipedia.org/wiki/Unix_time
There is no need to use jQuery as other than this alias, it does little else to help with date/time manipulation.
If you are looking for a quick and dirty way of representing the time in text, the Javascript Date object has a "toString" prototype that will return an ISO formatted Date Time.
new Date().toString();
//returns "Thu Apr 30 2015 14:37:36 GMT+0100 (BST)"
More than likely though, you will want to customize your formatting. The Date object has the ability to pull out your relevant details so you can build your own string representation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var d = new Date(); //without params it defaults to "now"
var t = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
//Will return 14:37:36
However, as you have asked for a jQuery solution - it is perhaps likely that you are working with older browsers. If you want to do more specific things - especially interpreting strings into Date objects (useful for API responses), you might want to look at Moment.js.
This will ensure cross browser compatibility and has much improved formatting without having to concatenate lots of strings to together! For example:
moment().format('hh:mm:ss');
//Will return 14:37:36
why not simply:
./aaa.sh 2>&1 | tee -a log
This simply redirects stderr
to stdout
, so tee echoes both to log and to screen. Maybe I'm missing something, because some of the other solutions seem really complicated.
Note: Since bash version 4 you may use |&
as an abbreviation for 2>&1 |
:
./aaa.sh |& tee -a log
You are calling GridView.RenderControl(htmlTextWriter)
, hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
Managing a connection (or a pool of connections) to a database.
I would use it also to retrieve and store informations on external configuration files.
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Expanding on mVck's answer above, the following logic determines whether "Never ask again" has been checked for a given Permission Request:
bool bStorage = grantResults[0] == Permission.Granted;
bool bNeverAskForStorage =
!bStorage && (
_bStorageRationaleBefore == true && _bStorageRationaleAfter == false ||
_bStorageRationaleBefore == false && _bStorageRationaleAfter == false
);
which is excerpted from below (for the full example see this answer)
private bool _bStorageRationaleBefore;
private bool _bStorageRationaleAfter;
private const int ANDROID_PERMISSION_REQUEST_CODE__SDCARD = 2;
//private const int ANDROID_PERMISSION_REQUEST_CODE__CAMERA = 1;
private const int ANDROID_PERMISSION_REQUEST_CODE__NONE = 0;
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case ANDROID_PERMISSION_REQUEST_CODE__SDCARD:
_bStorageRationaleAfter = ShouldShowRequestPermissionRationale(Android.Manifest.Permission.WriteExternalStorage);
bool bStorage = grantResults[0] == Permission.Granted;
bool bNeverAskForStorage =
!bStorage && (
_bStorageRationaleBefore == true && _bStorageRationaleAfter == false ||
_bStorageRationaleBefore == false && _bStorageRationaleAfter == false
);
break;
}
}
private List<string> GetRequiredPermissions(out int requestCode)
{
// Android v6 requires explicit permission granting from user at runtime for security reasons
requestCode = ANDROID_PERMISSION_REQUEST_CODE__NONE; // 0
List<string> requiredPermissions = new List<string>();
_bStorageRationaleBefore = ShouldShowRequestPermissionRationale(Android.Manifest.Permission.WriteExternalStorage);
Permission writeExternalStoragePerm = ApplicationContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage);
//if(extStoragePerm == Permission.Denied)
if (writeExternalStoragePerm != Permission.Granted)
{
requestCode |= ANDROID_PERMISSION_REQUEST_CODE__SDCARD;
requiredPermissions.Add(Android.Manifest.Permission.WriteExternalStorage);
}
return requiredPermissions;
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Android v6 requires explicit permission granting from user at runtime for security reasons
int requestCode;
List<string> requiredPermissions = GetRequiredPermissions(out requestCode);
if (requiredPermissions != null && requiredPermissions.Count > 0)
{
if (requestCode >= ANDROID_PERMISSION_REQUEST_CODE__SDCARD)
{
_savedInstanceState = savedInstanceState;
RequestPermissions(requiredPermissions.ToArray(), requestCode);
return;
}
}
}
OnCreate2(savedInstanceState);
}
So i tried the above :javascript which works :) However HAML wraps the generated code in CDATA like so:
<script type="text/javascript">
//<![CDATA[
$(document).ready( function() {
$('body').addClass( 'test' );
} );
//]]>
</script>
The following HAML will generate the typical tag for including (for example) typekit or google analytics code.
%script{:type=>"text/javascript"}
//your code goes here - dont forget the indent!
Personally,
None of the answers above worked for me, I still kept getting NoClassDefFound errors (I am using Maven for dependencies). My solution was to build using "mvn clean install" and use the "[project]-jar-with-dependencies.jar" that that command creates. Similarly in Eclipse you can right click the project -> Run As -> Maven Install and it will place the jars in the target folder.
Why not just doing it this way?
DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;
Hope this helps.
There is one very interesting application by Stéphane Sudre which does all of this for you, is scriptable / supports building from the command line, has a super nice GUI and is FREE. Sad thing is: it's called "Packages" which makes it impossible to find in google.
http://s.sudre.free.fr/Software/Packages/about.html
I wished I had known about it before I started handcrafting my own scripts.
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group
or to order by the count
SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC
To develop the answer of @Caumons:
Imagine one father class has many children and there is a need to add a common field into that class. If you consider the mentioned approach, you should go to each children class one by one and refactor their constructors for the new field. therefore that solution is not a promising solution in this scenario
Now take a look at this solution.
A father can receive an self object from each children. Here is a father class:
public class Father {
protected String fatherField;
public Father(Father a){
fatherField = a.fatherField;
}
//Second constructor
public Father(String fatherField){
this.fatherField = fatherField;
}
//.... Other constructors + Getters and Setters for the Fields
}
Here is our child class that should implement one of its father constructor, in this case the aforementioned constructor :
public class Child extends Father {
protected String childField;
public Child(Father father, String childField ) {
super(father);
this.childField = childField;
}
//.... Other constructors + Getters and Setters for the Fields
@Override
public String toString() {
return String.format("Father Field is: %s\nChild Field is: %s", fatherField, childField);
}
}
Now we test out application:
public class Test {
public static void main(String[] args) {
Father fatherObj = new Father("Father String");
Child child = new Child(fatherObj, "Child String");
System.out.println(child);
}
}
And here is the result :
Father Field is: Father String
Child Field is: Child String
Now you can easily add new fields to father class without being worried of your children codes to break;
Running the jar from command line by:
C:\folder\where\jar\stored>java -jar JarName.jar
I got information which made the problem clearer:
main/Main has been compiled by a more recent version of the Java Runtime
In this case jar was compiled with version newer than jre supports.
Apart from the solutions already mentioned, you can also download jquery.min.js
locally and then use it -
For downloading -
wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"
manifest.json -
"content_scripts": [
{
"js": ["/path/to/jquery.min.js", ...]
}
],
in html -
<script src="/path/to/jquery.min.js"></script>
Reference - https://developer.chrome.com/extensions/contentSecurityPolicy
google-services.json file is unnecessary to receive notifications. Just add a variable for each flavour in your build.gradle file:
buildConfigField "String", "GCM_SENDER_ID", "\"111111111111\""
Use this variable BuildConfig.GCM_SENDER_ID instead of getString(R.string.gcm_defaultSenderId) while registering:
instanceID.getToken(BuildConfig.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
My nginx on Ubuntu is "nginx version: nginx/1.9.12 (Ubuntu)" and root path is /var/www/html/
Ubuntu info is : No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 16.04 LTS Release: 16.04 Codename: xenial
Actually, if you just installed nginx on Ubuntu, then you can go to "/etc/nginx/sites-available" and check the default file, there is a configuration like "root /web/root/path/goes/here". And that is what you are looking for.
Interestingly enough, importing os.path will import all of os. try the following in the interactive prompt:
import os.path
dir(os)
The result will be the same as if you just imported os. This is because os.path will refer to a different module based on which operating system you have, so python will import os to determine which module to load for path.
With some modules, saying import foo
will not expose foo.bar
, so I guess it really depends the design of the specific module.
In general, just importing the explicit modules you need should be marginally faster. On my machine:
import os.path
: 7.54285810068e-06
seconds
import os
: 9.21904878972e-06
seconds
These times are close enough to be fairly negligible. Your program may need to use other modules from os
either now or at a later time, so usually it makes sense just to sacrifice the two microseconds and use import os
to avoid this error at a later time. I usually side with just importing os as a whole, but can see why some would prefer import os.path
to technically be more efficient and convey to readers of the code that that is the only part of the os
module that will need to be used. It essentially boils down to a style question in my mind.
As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:
val person = new Person("Kumar",12)
Another possibility would be:
def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)
However, person.age=20
in your code is allowed, as you get back a Person
instance from the person
method, and on this instance you are allowed to change the value of a var
. The problem is, that after that line you have no more reference to that instance (as every call to person
will produce a new instance).
This is nothing special, you would have exactly the same behavior in Java:
class Person{
public int age;
private String name;
public Person(String name; int age) {
this.name = name;
this.age = age;
}
public String name(){ return name; }
}
public Person person() {
return new Person("Kumar", 12);
}
person().age = 20;
System.out.println(person().age); //--> 12
The -expandproperty does not work with more than 1 object. You can use this one :
Select-Object Name | ForEach-Object {$_.Name}
If there is more than one value then :
Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}
So far, I've seen this issue happen within corporate networks because of two reasons, one or both of which may be happening in your case:
As a side note, No. 2 above may make you feel uneasy about your supposedly secure TLS traffic being scanned. That's the corporate world for you.
It appears I cannot use an if statement.
Arrow functions either allow to use an expression or a block as their body. Passing an expression
foo => bar
is equivalent to the following block
foo => { return bar; }
However,
if (person.age > 18) person
is not an expression, if
is a statement. Hence you would have to use a block, if you wanted to use if
in an arrow function:
foo => { if (person.age > 18) return person; }
While that technically solves the problem, this a confusing use of .filter
, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter
should return a Boolean, i.e. true
or false
, indicating whether the element should be included in the new array or not.
So all you need is
family.filter(person => person.age > 18);
In ES5:
family.filter(function (person) {
return person.age > 18;
});
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
I think there is a simpler way:
public async Task<string> CreateSoapEnvelope()
{
string soapString = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<HelloWorld xmlns=""http://tempuri.org/"" />
</soap:Body>
</soap:Envelope>";
HttpResponseMessage response = await PostXmlRequest("your_url_here", soapString);
string content = await response.Content.ReadAsStringAsync();
return content;
}
public static async Task<HttpResponseMessage> PostXmlRequest(string baseUrl, string xmlString)
{
using (var httpClient = new HttpClient())
{
var httpContent = new StringContent(xmlString, Encoding.UTF8, "text/xml");
httpContent.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld");
return await httpClient.PostAsync(baseUrl, httpContent);
}
}
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
@ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
Please check your Windows system event log for any errors specifically for the "Event Source: Dhcp". It's very likely a networking error related to DHCP. Address lease time expired or so. It shouldn't be a problem related to the SQL Server or the query itself.
Just search the internet for "The semaphore timeout period has expired" and you'll get plenty of suggestions what might be a solution for your problem. Unfortunately there doesn't seem to be the solution for this problem.
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
I found that the following is useful if you need the return value:
result = %x[ls]
puts result
I specifically wanted to list the pids of all the Java processes on my machine, and used this:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
Since you don't use any suffix, the literals 13
and 4
are interpreted as integer:
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
Thus, since you declare 13
as integer, integer division will be performed:
For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.
The predefined division operators are listed below. The operators all compute the quotient of x and y.
Integer division:
int operator /(int x, int y); uint operator /(uint x, uint y); long operator /(long x, long y); ulong operator /(ulong x, ulong y);
And so rounding down occurs:
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.
If you do the following:
int x = 13f / 4f;
You'll receive a compiler error, since a floating-point division (the /
operator of 13f
) results in a float, which cannot be cast to int implicitly.
If you want the division to be a floating-point division, you'll have to make the result a float:
float x = 13 / 4;
Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0
. To explicitly declare the operands as float, using the f
suffix (13f
, 4f
).
Recursive function example:
def recursive(string, num):
print "#%s - %s" % (string, num)
recursive(string, num+1)
Run it with:
recursive("Hello world", 0)
From Wikipedia,
A database management system (DBMS) is a computer software application that interacts with the user, other applications, and the database itself to capture and analyze data. A general-purpose DBMS is designed to allow the definition, creation, querying, update, and administration of databases.
There are different types of DBMS products: relational, network and hierarchical
. The most widely commonly used type of DBMS today is the Relational Database Management Systems (RDBMS
)
DBMS:
RDBMS:
Have a look at this article for more details.
Simplest working solution for flow window (tested at Chrome):
<form action='...' method=post target="result" onsubmit="window.open('','result','width=800,height=400');">
<input name="..">
....
</form>
You cannot animate two things (like zoom in and go to my location) in one google map?
From a coding standpoint, you would do them sequentially:
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
Here, I move the camera first, then animate the camera, though both could be animateCamera()
calls. Whether GoogleMap
consolidates these into a single event, I can't say, as it goes by too fast. :-)
Here is the sample project from which I pulled the above code.
Sorry, this answer is flawed. See Rob's answer for a way to truly do this in one shot, by creating a CameraPosition
and then creating a CameraUpdate
from that CameraPosition
.
It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
I faced the same issue , it resolved by below change in pom.xml :
<build>
<testSourceDirectory>test</testSourceDirectory>
...
changed to:
<build>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
input -webkit-appearance: none;
alone does not work.
Try adding -webkit-border-radius:0px;
in addition.