Also you can use onclick="do_something(this)"
inside element
To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
CALL SP_Reporting_2(tablename);
END IF;
END;
CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
#proceed with code
END;
Use getpass for this purpose.
getpass.getpass - Prompt the user for a password without echoing
This is the first answer when Googling 'require': cannot load such file -- ubygems (LoadError)
after Google autocorrected "ubygems" to "rubygems". Turns out this was an intentional change between Ruby 2.4 and 2.5 (Bug #14322). Scripts that detect the user gems directory without taking into account the ruby version will most likely fail.
Ruby 2.4
ruby -rubygems -e 'puts Gem.user_dir'
Ruby 2.5
ruby -rrubygems -e 'puts Gem.user_dir'
Example:
<songs>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
<title>Kallichore</title>
<artist>Jewitt K. Sheppard</artist>
</song>
then:
<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Output on your browser: Ship of Nomads
credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
Also note that a result code in the second column refers to the properties of the file. For example:
U filename.1
U filename.2
UU filename.3
filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated
Convert an image to Base64 string in Android:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Simpler, using string interpolation instead of String.Format
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
or using yourVariable
double yourVariable = 12456.0;
$"{yourVariable:n0}";
$"{yourVariable:n2}";
long timeNow = System.currentTimeMillis();
System.out.println(new Date(timeNow));
Fri Apr 04 14:27:05 PDT 2014
I recently used this to read all the lines from a file:
alist = open('maze.txt').read().split()
or you can use this for that little bit of extra added safety:
with f as open('maze.txt'):
alist = f.read().split()
It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: ''
for every empty line, such as a newline at the end of the file.
class c1
{
event EventHandler someEvent;
ResetSubscriptions() => someEvent = delegate { };
}
It is better to use delegate { }
than null
to avoid the null ref exception.
You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.
In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.
If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.
If you want to search for multilines by the character literal, remember to check the rightmost regex icon.
In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.
Psutil suggested by Mark, is really the best solution, its only drawback is the GPL compatible license. If that's a problem, then you can invoke Windows' process info commands: wmic process
where WMI is available (XP pro, vista, win7) or tasklist
. Here is a description to do it: How to call an external program in python and retrieve the output and return code? (not the only possible way...)
The inline comments in Python starts with a hash character.
hello = "Hello!" # This is an inline comment
print(hello)
Hello!
Note that a hash character within a string literal is just a hash character.
dial = "Dial #100 to make an emergency call."
print(dial)
Dial #100 to make an emergency call.
A hash character can also be used for single or multiple lines comments.
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
Hello
World
Enclose the text with triple double quotes to support docstring.
def say_hello(name):
"""
This is docstring comment and
it's support multi line.
:param name it's your name
:type name str
"""
return "Hello " + name + '!'
print(say_hello("John"))
Hello John!
Enclose the text with triple single quotes for block comments.
'''
I don't care the parameters and
docstrings here.
'''
pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static
can also confer performance benefits in the presence of compiler optimizations.
Because a static
function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.
This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.
Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day
component of the date, so 2016-07-13
and 2016-07-16
would both be 2016-07-01
- thus making them equal by month.
If you have a date
(not a datetime
) value, then you can zero it directly:
SELECT
DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
COUNT(*)
FROM
[Table]
GROUP BY
DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )
If you have datetime
values, you'll need to use CONVERT
to remove the time-of-day portion:
SELECT
DATEADD( day, 1 - DATEPART( day, [Date] ), CONVERT( date, [Date] ) ),
COUNT(*)
FROM
[Table]
GROUP BY
DATEADD( day, 1 - DATEPART( day, [Date] ), CONVERT( date, [Date] ) )
To force download you may use Content-Type: application/force-download
header, which is supported by most browsers:
function downloadFile($filePath)
{
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
A BETTER WAY
Downloading files this way is not the best idea especially for large files. PHP will require extra CPU / Memory to read and output file contents and when dealing with large files may reach time / memory limits.
A better way would be to use PHP to authenticate and grant access to a file, and actual file serving should be delegated to a web server using X-SENDFILE method (requires some web server configuration):
X-SENDFILE
is natively supported by Lighttpd: https://redmine.lighttpd.net/projects/1/wiki/X-LIGHTTPD-send-filemod_xsendfile
module: https://tn123.org/mod_xsendfile/ On Ubuntu may be installed by: apt install libapache2-mod-xsendfile
X-Accel-Redirect
header: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/After configuring web server to handle X-SENDFILE
, just replace readfile($filePath)
with header('X-SENDFILE: ' . $filePath)
and web server will take care of file serving, which will require less resources than using PHP readfile
.
(For Nginx use X-Accel-Redirect
header instead of X-SENDFILE
)
Note: If you end up downloading empty files, it means you didn't configure your web server to handle X-SENDFILE
header. Check the links above to see how to correctly configure your web server.
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.
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
This gleaned from Twiggy @ http://archive.atomicmpc.com.au and other places:
'since the file name and path were used several times in code
'variables were made public
Public FName As Variant, Filename As String, Path As String
Sub xxx()
...
If Not GetFileName = 1 Then Exit Sub '
...
End Sub
Private Function GetFileName()
GetFileName = 0 'used for error handling at call point in case user cancels
FName = Application.GetOpenFilename("Ramp log file (*.txt), *.txt")
If Not VarType(FName) = vbBoolean Then GetFileName = 1 'to assure selection was made
Filename = Split(FName, "\")(UBound(Split(FName, "\"))) 'results in file name
Path = Left(FName, InStrRev(FName, "\")) 'results in path
End Function
Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object
function newUYDate(pDate) {
let dd = pDate.split("/")[0].padStart(2, "0");
let mm = pDate.split("/")[1].padStart(2, "0");
let yyyy = pDate.split("/")[2].split(" ")[0];
let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
mm = (parseInt(mm) - 1).toString(); // January is 0
return new Date(yyyy, mm, dd, hh, mi, secs);
}
I've been testing alternatives to C# Web browser component for few days now and here is my list:
1. Using newer IE versions 8,9:
Web Browser component is IE7 not IE8? How to change this?
Pros:
Cons:
This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.
OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari
Pros:
Cons:
OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..
I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.
3. GeckoFX
Pros:
Cons:
GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.
I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:
If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
On Windows:
Go to Win -> Control Panel -> Credential Manager -> Windows Credentials
Search for github address and remove it.
Then try to execute:
git push -u origin master
Windows will ask for your git credentials again, put the right ones and that's it.
Traceback (most recent call last):
File "tkwindowwithlabel5.py", line 23, in <module>
main()
File "tkwindowwithlabel5.py", line 16, in main
window.resizeable(width = True, height =True)
File "/usr/lib/python3.4/tkinter/__init__.py", line 1935, in
__getattr__
return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'resizeable'
is what you will get with the first answer. tk does support min and max size
window.minsize(width = X, height = x)
window.maxsize(width = X, height = x)
i figured it out but just trying the first one. using python3 with tk.
Last chance (if other ways don't work): define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH macro in all projects. It will disable "#pragma detect_mismatch" feature which is used in CRT headers.
Android does not run X Windows, nor does it have many of the standard GNU libraries. So, since most native linux applications require one or both of these, most will not run.
In addition, even Java programs can be limited, because the version of Java that Android applications are written in is a subset of the standard Java library.
There is an Apple style Gallery Slider over at http://www.jqueryfordesigners.com/slider-gallery/ which uses jQuery and the UI.
You may be interested in the csv
module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.
import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]
for row in csv.reader( lines ):
...
Why use Regex when you can simply use the Trim() method
Text='<%# Eval("FieldDescription").ToString().Trim() %>'
OR
string test = "Testing ";
test.Trim();
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
The <appSettings>
tag in web.config supports a file attribute that will load an external config with it's own set of key/values. These will override any settings you have in your web.config or add to them.
We take advantage of this by modifying our web.config at install time with a file attribute that matches the environment the site is being installed to. We do this with a switch on our installer.
eg;
<appSettings file=".\EnvironmentSpecificConfigurations\dev.config">
<appSettings file=".\EnvironmentSpecificConfigurations\qa.config">
<appSettings file=".\EnvironmentSpecificConfigurations\production.config">
Note:
Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.
However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".
Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.
Here is a much simpler way to go back to a previous commit (and have it in an uncommited state, to do with it whatever you like):
git reset HEAD~1
So, no need for commit ids and so on :)
I haven't had any problems with this code:
private bool IsValidPath(string path, bool exactPath = true)
{
bool isValid = true;
try
{
string fullPath = Path.GetFullPath(path);
if (exactPath)
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
else
{
isValid = Path.IsPathRooted(path);
}
}
catch(Exception ex)
{
isValid = false;
}
return isValid;
}
For example these would return false:
IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", false);
And these would return true:
IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", false);
if you're connecting to a postgres database, the following works:
result = cursor.execute(query)
if result.returns_rows:
# we got rows!
return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
return None
An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:
void foo(X& x); // lvalue reference overload
void foo(X&& x); // rvalue reference overload
X x;
X foobar();
foo(x); // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)
So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.
It is almost easier to understand first what rvalues accomplish with an example:
#include <cstring>
class Sample {
int *ptr; // large block of memory
int size;
public:
Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz}
{
if (ptr != nullptr) memset(ptr, 0, sz);
}
// copy constructor that takes lvalue
Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
nullptr}, size{s.size}
{
if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
std::cout << "copy constructor called on lvalue\n";
}
// move constructor that take rvalue
Sample(Sample&& s)
{ // steal s's resources
ptr = s.ptr;
size = s.size;
s.ptr = nullptr; // destructive write
s.size = 0;
cout << "Move constructor called on rvalue." << std::endl;
}
// normal copy assignment operator taking lvalue
Sample& operator=(const Sample& s)
{
if(this != &s) {
delete [] ptr; // free current pointer
size = s.size;
if (size != 0) {
ptr = new int[s.size];
memcpy(ptr, s.ptr, s.size);
} else
ptr = nullptr;
}
cout << "Copy Assignment called on lvalue." << std::endl;
return *this;
}
// overloaded move assignment operator taking rvalue
Sample& operator=(Sample&& lhs)
{
if(this != &s) {
delete [] ptr; //don't let ptr be orphaned
ptr = lhs.ptr; //but now "steal" lhs, don't clone it.
size = lhs.size;
lhs.ptr = nullptr; // lhs's new "stolen" state
lhs.size = 0;
}
cout << "Move Assignment called on rvalue" << std::endl;
return *this;
}
//...snip
};
The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.
The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.
Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).
One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:
template<class T> class unique_ptr {
//...snip
unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};
std::unique_ptr<int[] pt1{new int[10]};
std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.
// So we must first cast ptr1 to an rvalue
std::unique_ptr<int[]> ptr2{std::move(ptr1)};
std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
int size)
{
for (auto i = 0; i < size; ++i) {
param[i] += 10;
}
return param; // implicitly calls unique_ptr(unique_ptr&&)
}
// Now use function
unique_ptr<int[]> ptr{new int[10]};
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
static_cast<unique_ptr<int[]>&&>(ptr), 10);
cout << "output:\n";
for(auto i = 0; i< 10; ++i) {
cout << new_owner[i] << ", ";
}
output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
static_cast<unique_ptr<int[]>&&>(ptr)
is usually done using std::move
// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);
An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.
A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al
A function which works in both bash and zsh:
# Return the first pathname in $PATH for name in $1
function cmd_path () {
if [[ $ZSH_VERSION ]]; then
whence -cp "$1" 2> /dev/null
else # bash
type -P "$1" # No output if not in $PATH
fi
}
Non-zero is returned if the command is not found in $PATH
.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
In Xcode 10 the OS_ACTIVITY_MODE
variable with disable
(or default
) value also turns off the NSLog
no matter what.
So if you want to get rid of the console noise but not of your own logs, you could try the good old printf("")
instead of the NSLog since it is not affected by the OS_ACTIVITY_MODE
= disable
.
But better check out the new os_log
API here.
Just another option for all the IE8 lovers, and it works perfect in newer browsers. You can just color the text to match the background of the input. If you have a single field, this will change the color to black when you click/focus on the field. I would not use this on a public site since it would 'confuse' most people, but I am using it in an ADMIN section where only one person has access to the users passwords.
$('#MyPass').click(function() {
$(this).css('color', '#000000');
});
-OR-
$('#MyPass').focus(function() {
$(this).css('color', '#000000');
});
This, also needed, will change the text back to white when you leave the field. Simple, simple, simple.
$("#MyPass").blur(function() {
$(this).css('color', '#ffffff');
});
[ Another Option ] Now, if you have several fields that you are checking for, all with the same ID, as I am using it for, add a class of 'pass' to the fields you want to hide the text in. Set the password fields type to 'text'. This way, only the fields with a class of 'pass' will be changed.
<input type="text" class="pass" id="inp_2" value="snoogle"/>
$('[id^=inp_]').click(function() {
if ($(this).hasClass("pass")) {
$(this).css('color', '#000000');
}
// rest of code
});
Here is the second part of this. This changes the text back to white after you leave the field.
$("[id^=inp_]").blur(function() {
if ($(this).hasClass("pass")) {
$(this).css('color', '#ffffff');
}
// rest of code
});
If visibility property set to "hidden"
, the browser will still take space on the page for the content even though it's invisible.
But when we set an object to "display:none"
, the browser does not allocate space on the page for its content.
Example:
<div style="display:none">
Content not display on screen and even space not taken.
</div>
<div style="visibility:hidden">
Content not display on screen but it will take space on screen.
</div>
this is the FASTEST (most readable, least complicated) way to do it, Owens works but it's not legal HTML, technically this answer is not jQuery (but since jQuery is a pre-prepared pseudocode - reinterpreted on the client platform as native JavaScript - there really is no such thing as jQuery anyway)
<button onclick="window.location.href='http://www.google.com';">Google</button>
configure project in android studio from eclipse: you have to import eclipse ndk project to android studio without exporting to gradle and it works , also you need to add path of ndk in local.properties ,if shows error then add
sourceSets.main {
jniLibs.srcDir 'src/main/libs'
jni.srcDirs = [] //disable automatic ndk-build callenter code here
}
in build.gradle file then create jni folder and file using terminal and run it will work
Only use Redim
statement
Dim aFirstArray() As Variant
Redim aFirstArray(nRows,nColumns)
giving position: absolute;
to the child worked in my case
I tried all the possible commands listed above and none of them worked for me, Check if Package.json contain "@angular-devkit/build-angular" if not just install it using(in my case version 0.803.19 worked)
npm i @angular-devkit/[email protected]
Or checkout at npm website repositories for version selection
I Got the same error.
I just added the @Transactional annotation of javax.transaction.Transactional on the method.
In general use serialize()
on the form element.
Please be mindful that multiple <select> options are serialized under the same key, e.g.
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}
which turns the above into:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
var inputs = compress($("#your-form").serialize());
Hope that helps.
complimentary to the above code I wanted to remove the beginning of the string and could not find a reference anywhere. Here is how I did it:
var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range) // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description
This trims 17 characters from the beginning of the string (he total string length is 67 we advance -50 from the end and there you have it.
Considering you want to check for ASCII Alphanumeric characters, Try this:
"^[a-zA-Z0-9]*$"
. Use this RegEx in String.matches(Regex)
, it will return true if the string is alphanumeric, else it will return false.
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}
If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html
Apps targeting Android Q - API 29 by default are given a filtered view into external storage. A quick fix for that is to add this code in the AndroidManifest.xml:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
Read more about it here: https://developer.android.com/training/data-storage/compatibility
PJL is right. I have used his suggestion and this is what i have done:
defined global variables for fragment:
private final Object attachingActivityLock = new Object();
private boolean syncVariable = false;
implemented
@Override public void onAttach(Activity activity) { super.onAttach(activity); synchronized (attachingActivityLock) { syncVariable = true; attachingActivityLock.notifyAll(); } }
3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.
Thread processImage = new Thread(new Runnable() {
@Override
public void run() {
processImage();
}
});
processImage.start();
4 . in my function where I need to call getActivity(), I use this (before the call getActivity())
synchronized (attachingActivityLock) {
while(!syncVariable){
try {
attachingActivityLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:
image.post(new Runnable() {
@Override
public void run() {
image.setImageBitmap(imageToShow);
}
});
Not tested, but you can do something like this:
Create Function dbo.AlphasOnly(@s as varchar(max)) Returns varchar(max) As
Begin
Declare @Pos int = 1
Declare @Ret varchar(max) = null
If @s Is Not Null
Begin
Set @Ret = ''
While @Pos <= Len(@s)
Begin
If SubString(@s, @Pos, 1) Like '[A-Za-z]'
Begin
Set @Ret = @Ret + SubString(@s, @Pos, 1)
End
Set @Pos = @Pos + 1
End
End
Return @Ret
End
The key is to use this as a computed column and index it. It doesn't really matter how fast you make this function if the database has to execute it against every row in your large table every time you run the query.
You can see the default value in Chrome in this link
int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes
In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.
This command worked for me,
sudo chown -v $USER ~/.ssh/known_hosts
as mentioned by @kenorb.
The error was coming due to broken permissions, for the current user.
You just make div
s like this:
<div style="width:100px; height: 100px; border:1px solid; overflow:hidden; ">
<br/>
<div style="position:inherit; width: 200px; height:200px; background:yellow;">
<br/>
<div style="position:absolute; width: 500px; height:50px; background:Pink; z-index: 99;">
<br/>
</div>
</div>
</div>
I hope this code will help you :)
PHP renders HTML and Javascript to send to the client's browser. PHP is a server-side language. This is what allows it do things like INSERT something into a database on the server.
But an alert is rendered by the browser of the client. You would have to work through javascript to get an alert.
This is because the Python exec are not in the search path of your operating system. In windows, start CMD. Type in
setx PATH PythonPath
where PythonPath is usually C:\Python27
or C:\Python33
or C:\Users\<Your User Name>\AppData\Local\Programs\Python\Python37
depending on your Python version. After restarting the CMD, you should get see outcomes when typing
Python --version
Here are the standard punctuation characters for US-ASCII: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
For Unicode punctuation (such as curly quotes, em-dashes, etc), you can easily match on specific block ranges. The General Punctuation block is \u2000-\u206F
, and the Supplemental Punctuation block is \u2E00-\u2E7F
.
Put together, and properly escaped, you get the following RegExp:
/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/
That should match pretty much any punctuation you encounter. So, to answer the original question:
var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');
>> "This is an example of a string with punctuation"
US-ASCII source: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix
Unicode source: http://kourge.net/projects/regexp-unicode-block
From Wikipedia (emphasis and link added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
So, the real percent encoding uses %20
while form data in URLs is in a modified form that uses +
. So you're most likely to only see +
in URLs in the query string after an ?
.
Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).
This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.
More great info here:
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
It can be done all on the client-side using the OnClientClick
[MSDN] event handler and window.open
[MDN]:
<asp:Button
runat="server"
OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
Open a new window!
</asp:Button>
Because we are running on Ubuntu 12.04 LTS and the latest official supported tomcat7 package is 7.0.26 we are not easily able to update the whole tomcat.
I order to test for with the jdk8, I was able to get resolve this issue by changing some jars against their latest 7.0.* version.
I switched jasper.jar, jasper-el and tomcat-util to the version 7.0.53 and added ecj-4.3.1.jar. That brings the application back online.
BUT... also i changed packaged content with this, so maybe it would be better to download the whole tomcat and use it self installed as messing up packages. So please see this only as a very dirty quickhack or workaround.
Inserting data into a pandas dataframe and providing column name.
import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df) #printing dataframe.
This is our printed data:
For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.
Like this:
df['COUNTER'] =1 #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)
OUTPUT:
Check that ORACLE_HOME environment variable is pointing to the correct oracle home. In my case it was changed by another software installation.
You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.
You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.
ALTER DATABASE MyDB SET RECOVERY SIMPLE;
In my case simply restarting the WiFi router helped.
For a similar effect to form's target
attribute, you can also use the formtarget
attribute of input[type="submit]"
or button[type="submit"]
.
From MDN:
...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:
- _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
- _blank: Load the response into a new unnamed browsing context.
- _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
- _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
In addition to the answers already given, if you want to create a new directory, you could use this function:
def mkdir_p(mypath):
'''Creates a directory. equivalent to using mkdir -p on the command line'''
from errno import EEXIST
from os import makedirs,path
try:
makedirs(mypath)
except OSError as exc: # Python >2.5
if exc.errno == EEXIST and path.isdir(mypath):
pass
else: raise
and then:
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))
# Create new directory
output_dir = "some/new/directory"
mkdir_p(output_dir)
fig.savefig('{}/graph.png'.format(output_dir))
I had this issue when accessing actuator. Putting following configuration class solved the issue:
@Configuration
@EnableWebMvc
public class MediaConverterConfiguration implements WebMvcConfigurer {
@Bean
public MappingJackson2HttpMessageConverter jacksonConverter() {
MappingJackson2HttpMessageConverter mc =
new MappingJackson2HttpMessageConverter();
List<MediaType> supportedMediaTypes =
new ArrayList<>(mc.getSupportedMediaTypes());
supportedMediaTypes
.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
supportedMediaTypes.add(
MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
mc.setSupportedMediaTypes(supportedMediaTypes);
return mc;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonConverter());
}
}
With 1.1.1, I used the following to fix the scale between 0.0 and 1.0:
var options = {
scaleOverride: true,
scaleStartValue: 0,
scaleSteps: 10,
scaleStepWidth: 0.1
}
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
get file object....
File file = new File(filePath);
then....pass as a parameter to...
getMimeType(file);
...here is
public String getMimeType(File file) {
String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()).toLowerCase());
if (mimetype == null) {
return "*/*";
}
return mimetype;///return the mimeType
}
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range
you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2
not being found in the searched range Sheet1!A1:A65536
. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet
is Sheet1
, then using Range("D2")
without qualifying it will be searching for Sheet1!D2
, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup
(although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP
as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A
in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...
).
Using =VLOOKUP...
is fundamentally different from Application.WorksheetFunction.VLookup
: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).
A good way is to create a procedure:
create proc pagination (@startfrom int ,@endto int) as
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY name desc) as row FROM sys.databases
) a WHERE a.row > @startfrom and a.row <= @endto
just like limit 0,2 /////////////// execute pagination 0,4
For me I need to set current date and time as default value this solved my issue in View add this code :
<div class="form-group">
@Html.LabelFor(model => model.order_date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.order_date, new { htmlAttributes = new { @class = "form-control",@Value= DateTime.Now } })
@Html.ValidationMessageFor(model => model.order_date, "", new { @class = "text-danger" })
</div>
</div>
What about this:
otherfunction(thing_collection, thing)
Rather than expose something so implementation-dependent like a list index in a function interface, pass the collection and the thing and let otherfunction deal with the "test for membership" issues. If otherfunction is written to be collection-type-agnostic, then it would probably start with:
if thing in thing_collection:
... proceed with operation on thing
which will work if thing_collection is a list, tuple, set, or dict.
This is possibly clearer than:
if thing_index != MAGIC_VALUE_INDICATING_NOT_A_MEMBER:
which is the code you already have in otherfunction.
i had created new repo in github and i had the same problem, but it also had problem while pulling, so this worked for me.
but this is not advised in repos that already have many codes as this could mess up everything
git push origin master --force
Try this:
b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]
Since you are on 10g, you could potentially use the ORA_ROWSCN
pseudocolumn. That gives you an upper bound of the last SCN (system change number) that caused a change in the row. Since this is an increasing sequence, you could store off the maximum ORA_ROWSCN
that you've seen and then look only for data with an SCN greater than that.
By default, ORA_ROWSCN
is actually maintained at the block level, so a change to any row in a block will change the ORA_ROWSCN
for all rows in the block. This is probably quite sufficient if the intention is to minimize the number of rows you process multiple times with no changes if we're talking about "normal" data access patterns. You can rebuild the table with ROWDEPENDENCIES
which will cause the ORA_ROWSCN
to be tracked at the row level, which gives you more granular information but requires a one-time effort to rebuild the table.
Another option would be to configure something like Change Data Capture (CDC) and to make your OCI application a subscriber to changes to the table, but that also requires a one-time effort to configure CDC.
I am flabbergasted that no answer offered SQL window function solution:
SELECT a.id, a.rev, a.contents
FROM (SELECT id, rev, contents,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY rev DESC) rank
FROM YourTable) a
WHERE a.rank = 1
Added in SQL standard ANSI/ISO Standard SQL:2003 and later extended with ANSI/ISO Standard SQL:2008, window (or windowing) functions are available with all major vendors now. There are more types of rank functions available to deal with a tie issue: RANK, DENSE_RANK, PERSENT_RANK
.
I had v0.12.3 of Nodejs on Win7 x64 and ran into similar issues when I tried installing gulp. This worked for me:
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
You can size your label according to text and other related controls using two ways-
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : labelFont
}
context:nil].size;
before iOS 7.0 this could be used to calculate label size
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label
[label setText:@"label text to set"];
[label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
Playlist hack didn't work for me either. Working workaround for September 2018 (bonus: set width and height by CSS for #yt-wrap
instead of hard-coding it in JS):
<div id="yt-wrap">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="ytplayer"></div>
</div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
width: '100%',
height: '100%',
videoId: 'VIDEO_ID',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
player.mute(); // comment out if you don't want the auto played video muted
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
player.seekTo(0);
player.playVideo();
}
}
function stopVideo() {
player.stopVideo();
}
</script>
try to simply git restore .
That's what git says & it's working
It is generally considered bad practise to have a one to one relationship. This is because you could just have the data represented in one table and achieve the same result.
However, there are instances where you may not be able to make these changes to the table you are referencing. In this instance there is no problem using the Foreign key as the primary key. It might help to have a composite key consisting of an auto incrementing unique primary key and the foreign key.
I am currently working on a system where users can log in and generate a registration code to use with an app. For reasons I won't go into I am unable to simply add the columns required to the users table. So I am going down a one to one route with the codes table.
If you don't need an automated solution, you can find the thumbnail URL by entering the vimeo ID here: http://video.depone.eu/
Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
I've had such a task before and I've got the solution. I would avoid enumerating all days in between when it's avoidable, which is the case here. I don't even mention creating a bunch of DateTime instances, as I saw in one of the answers above. This is really waste of processing power. Especially in the real world situation, when you have to examine time intervals of several months. See my code, with comments, below.
/// <summary>
/// Calculates number of business days, taking into account:
/// - weekends (Saturdays and Sundays)
/// - bank holidays in the middle of the week
/// </summary>
/// <param name="firstDay">First day in the time interval</param>
/// <param name="lastDay">Last day in the time interval</param>
/// <param name="bankHolidays">List of bank holidays excluding weekends</param>
/// <returns>Number of business days during the 'span'</returns>
public static int BusinessDaysUntil(this DateTime firstDay, DateTime lastDay, params DateTime[] bankHolidays)
{
firstDay = firstDay.Date;
lastDay = lastDay.Date;
if (firstDay > lastDay)
throw new ArgumentException("Incorrect last day " + lastDay);
TimeSpan span = lastDay - firstDay;
int businessDays = span.Days + 1;
int fullWeekCount = businessDays / 7;
// find out if there are weekends during the time exceedng the full weeks
if (businessDays > fullWeekCount*7)
{
// we are here to find out if there is a 1-day or 2-days weekend
// in the time interval remaining after subtracting the complete weeks
int firstDayOfWeek = (int) firstDay.DayOfWeek;
int lastDayOfWeek = (int) lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)// Both Saturday and Sunday are in the remaining time interval
businessDays -= 2;
else if (lastDayOfWeek >= 6)// Only Saturday is in the remaining time interval
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)// Only Sunday is in the remaining time interval
businessDays -= 1;
}
// subtract the weekends during the full weeks in the interval
businessDays -= fullWeekCount + fullWeekCount;
// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}
return businessDays;
}
Edit by Slauma, August 2011
Great answer! There is little bug though. I take the freedom to edit this answer since the answerer is absent since 2009.
The code above assumes that DayOfWeek.Sunday
has the value 7
which is not the case. The value is actually 0
. It leads to a wrong calculation if for example firstDay
and lastDay
are both the same Sunday. The method returns 1
in this case but it should be 0
.
Easiest fix for this bug: Replace in the code above the lines where firstDayOfWeek
and lastDayOfWeek
are declared by the following:
int firstDayOfWeek = firstDay.DayOfWeek == DayOfWeek.Sunday
? 7 : (int)firstDay.DayOfWeek;
int lastDayOfWeek = lastDay.DayOfWeek == DayOfWeek.Sunday
? 7 : (int)lastDay.DayOfWeek;
Now the result is:
Michael Krelin's answer is close is not entirely safe, since it can be wrong in rare situations. The problem is that intervals in PostgreSQL do not have context with regards to things like daylight savings. Intervals store things internally as months, days, and seconds. Months aren't an issue in this case since subtracting two timestamps just use days and seconds but 'days' can be a problem.
If your subtraction involves daylight savings change-overs, a particular day might be considered 23 or 25 hours respectively. The interval will take that into account, which is useful for knowing the amount of days that passed in the symbolic sense but it would give an incorrect number of the actual hours that passed. Epoch on the interval will just multiply all days by 24 hours.
For example, if a full 'short' day passes and an additional hour of the next day, the interval will be recorded as one day and one hour. Which converted to epoch/3600 is 25 hours. But in reality 23 hours + 1 hour should be a total of 24 hours.
So the safer method is:
(EXTRACT(EPOCH FROM current_timestamp) - EXTRACT(EPOCH FROM somedate))/3600
As Michael mentioned in his follow-up comment, you'll also probably want to use floor() or round() to get the result as an integer value.
I know this doesn't answer the question exactly, but for ppl coming in from google that happen to use Gradle for their dependency management:
I managed to get rid of all xerces/Java8 issues with Gradle like this:
configurations {
all*.exclude group: 'xml-apis'
all*.exclude group: 'xerces'
}
Yes, you can do <property name="defaultLocale" value="#{ systemProperties['user.region']}"/>
for instance.
The variable systemProperties is predefined, see 6.4.1 XML based configuration.
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
context.clearRect(0, 0, canvas.width, canvas.height);
This is the fastest and most descriptive way to clear the entire canvas.
canvas.width = canvas.width;
Resetting canvas.width
resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.
If you have modified the transformation matrix (e.g. using scale
, rotate
, or translate
) then context.clearRect(0,0,canvas.width,canvas.height)
will likely not clear the entire visible portion of the canvas.
The solution? Reset the transformation matrix prior to clearing the canvas:
// Store the current transformation matrix
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore();
Edit: I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.
That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.
100000 iterations averaged 10 times:
1885ms to clear
2112ms to reset and clear
Public Function Round(ByVal text As TextBox) As Integer
Dim r As String = Nothing
If text.TextLength > 3 Then
Dim Last3 As String = (text.Text.Substring(text.Text.Length - 3))
If Last3.Substring(0, 1) = "." Then
Dim dimcalvalue As String = Last3.Substring(Last3.Length - 2)
If Val(dimcalvalue) >= 50 Then
text.Text = Val(text.Text) - Val(Last3)
text.Text = Val(text.Text) + 1
ElseIf Val(dimcalvalue) < 50 Then
text.Text = Val(text.Text) - Val(Last3)
End If
End If
End If
Return r
End Function
You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:
set nocount on
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
print @fullpath + char(9) + char(9) + 'file exists'
else
print @fullpath + char(9) + char(9) + 'file does not exists'
fetch from cur into @fullpath
end
close cur
deallocate cur
or you can put it in a tempTable if you want to integrate it in your frontend..
create proc GetFileStatus as
begin
set nocount on
create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
insert into #tempFileStatus values(@fullpath,'File exist')
else
insert into #tempFileStatus values(@fullpath,'File does not exists')
fetch from cur into @fullpath
end
close cur
deallocate cur
select * from #tempFileStatus
drop table #tempFileStatus
end
then call it using:
exec GetFileStatus
No, you don't need to make criteria query it would be boilerplate code you just do simple thing if you working in Spring-boot: in your repo declare a method name with findBy[exact field name]. Example- if your model or document consist a string field myField and you want to find by it then your method name will be:
findBymyField(String myField);
You have to create a password file: see http://www.postgresql.org/docs/9.0/interactive/libpq-pgpass.html for more info.
id="hiddenBtn"
and type="submit"
that do the submittype="button"
set onclick
of the current button call a function
look like below:
function foo() {
// do something before submit
...
// trigger click event of the hidden button
$('#hinddenBtn').trigger("click");
}
You should use finish()
when the user clicks on the button in order to go to the previous activity.
Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Alternatively, if you really need to, you can try to trigger your own back key press:
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Execute both of these.
You can use jquery attr method
$("#delete").attr("hidden",true);
If you configure the SWAGGER to your spring boot application, and invoke any API from your application there you can see that CURL Request as well.
I think this is the easy way of generating the requests through the CURL.
Console.Log
// get a new date (locale machine date time)_x000D_
var date = new Date();_x000D_
// get the date as a string_x000D_
var n = date.toDateString();_x000D_
// get the time as a string_x000D_
var time = date.toLocaleTimeString();_x000D_
_x000D_
// log the date in the browser console_x000D_
console.log('date:', n);_x000D_
// log the time in the browser console_x000D_
console.log('time:',time);
_x000D_
DIV
// get a new date (locale machine date time)_x000D_
var date = new Date();_x000D_
// get the date as a string_x000D_
var n = date.toDateString();_x000D_
// get the time as a string_x000D_
var time = date.toLocaleTimeString();_x000D_
_x000D_
// find the html element with the id of time_x000D_
// set the innerHTML of that element to the date a space the time_x000D_
document.getElementById('time').innerHTML = n + ' ' + time;
_x000D_
<div id='time'></div>
_x000D_
Note: these functions aren't fully cross browser supported
//Fri Aug 30 2013 4:36 pm_x000D_
console.log(formatAMPM(new Date()));_x000D_
_x000D_
//using your function (passing in date)_x000D_
function formatAMPM(date) {_x000D_
// gets the hours_x000D_
var hours = date.getHours();_x000D_
// gets the day_x000D_
var days = date.getDay();_x000D_
// gets the month_x000D_
var minutes = date.getMinutes();_x000D_
// gets AM/PM_x000D_
var ampm = hours >= 12 ? 'pm' : 'am';_x000D_
// converts hours to 12 hour instead of 24 hour_x000D_
hours = hours % 12;_x000D_
// converts 0 (midnight) to 12_x000D_
hours = hours ? hours : 12; // the hour '0' should be '12'_x000D_
// converts minutes to have leading 0_x000D_
minutes = minutes < 10 ? '0'+ minutes : minutes;_x000D_
_x000D_
// the time string_x000D_
var time = hours + ':' + minutes + ' ' + ampm;_x000D_
_x000D_
// gets the match for the date string we want_x000D_
var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);_x000D_
_x000D_
//the result_x000D_
return match[0] + ' ' + time;_x000D_
}
_x000D_
Change it to for(int i=0;i<=9;i++)
Here is my summary of this problem: 5 Ways of Calling Java from Python
http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)
Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype
I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.
Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)
n
- the predefined length of result arrays
Non-python data is best bundled inside your Python modules using the package_data
support in setuptools. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in com.yourcompany.yourproject
(and being able to have a shared com.yourcompany.utils
namespace).
Re branching and merging, if you use a good enough source control system it will handle merges even through renames; Bazaar is particularly good at this.
Contrary to some other answers here, I'm +1 on having a src
directory top-level (with doc
and test
directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; Sphinx, for instance, has its own conventions which its quickstart tool supports.
Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using package_data
).
If you just want to stop further code from executing without "throwing" any error, you can temporarily override window.onerror
as shown in cross-exit
:
function exit(code) {
const prevOnError = window.onerror
window.onerror = () => {
window.onerror = prevOnError
return true
}
throw new Error(`Script termination with code ${code || 0}.`)
}
console.log("This message is logged.");
exit();
console.log("This message isn't logged.");
If you are using the distro go, you should point to where the include files are, for example:
$ rpm -ql golang | grep include
/usr/lib/golang/include
(This is for Fedora 20)
I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.
Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.
Simple read loop use this code
var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);
foreach (DictionaryEntry dictionaryEntry in resx)
{
Console.WriteLine("Key: " + dictionaryEntry.Key);
Console.WriteLine("Val: " + dictionaryEntry.Value);
}
You need to create the project on GitHub first. After that go to the project directory and run in terminal:
git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master
javascript:history.go(-1);
was used in the older browser.IE6. For other browser compatibility try
window.history.go(-1);
where -1 represent the number of pages you want to go back (-1,-2...etc) and
return false
is required to prevent default event.
For example :
<a href="#" onclick="window.history.go(-1); return false;"> Link </a>
You like to set charset and unescaped unicode
header('Content-Type: application/json;charset=utf-8');
json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
There is an error on this line:
[img setImage:[UIImage imageNamed@"anyImageName"]];
It should be:
[img setImage:[UIImage imageNamed:@"anyImageName"]];
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
there is no requirement of any conversion.
We can simply use xdot command in Linux which is an Interactive viewer for Graphviz dot files.
ex: xdot file.dot
for more infor:https://github.com/rakhimov/cppdep/wiki/How-to-view-or-work-with-Graphviz-Dot-files
Just to add, you can also retrieve a jqGrid cell value, based on the rowID plus column index (rather than the Column name):
So, to fetch the value in the forth column (column index # 3) for the row with primary key ID 1234, we could use this:
var rowID = 1234;
var columnIndex = 3;
var cellValue = $("#" + rowID).find('td').eq(columnIndex).text();
Btw, on a completely unrelated topic (but please don't vote me down):
I didn't realise that you can, fairly easily, link text boxes to your jqGrid, so your users can do instant searching, without having to open the Search dialog.
To do this, you need a bit of HTML like this:
<input type="text" name="employeeName" id="employeeName" style="width:250px" />
<!-- This will be my jqGrid control and pager -->
<table id="tblEmployees"></table>
<div id="pager"></div>
And a bit of JavaScript like this:
$("#employeeName").on('change keyup paste', function () {
SearchByEmployeeName();
});
function SearchByEmployeeName()
{
// Fetch the text from our <input> control
var searchString = $("#employeeName").val();
// Prepare to pass a new search filter to our jqGrid
var f = { groupOp: "AND", rules: [] };
// Remember to change the following line to reflect the jqGrid column you want to search for your string in
// In this example, I'm searching through the UserName column.
f.rules.push({ field: "UserName", op: "cn", data: searchString });
var grid = $('#tblEmployees');
grid[0].p.search = f.rules.length > 0;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
This is a real game-changer for me... it really makes jqGrid much more user friendly.
Users can immediately start typing in their search string, rather than needing to open the Search dialog, remember to change the operator to "contains", then start typing, and close the search dialog again.
try it like this:
<div id="divContainer">
<div class="divImageHolder">
IMG HERE
</div>
<div class="divImageHolder">
IMG HERE
</div>
<div class="divImageHolder">
IMG HERE
</div>
<br class="clear" />
</div>
<style type="text/css">
#divContainer { margin: 0 auto; width: 800px; }
.divImageHolder { float:left; }
.clear { clear:both; }
</style>
A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.
Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.
In Android Studio, which, quite honestly, you should be using, change the package name by right-clicking
on the package name in the project structure -> Refactor -> Rename...
It then gives the option of renaming the directory or the package. Select the package. The directory should follow suit. Type in your new package name, and click Refactor. It will change all the imports and remove redundant imports for you. You can even have it fix it for you in comments and strings, etc.
Lastly, change the package name accordingly in your AndroidManifest.xml towards the top. Otherwise you will get errors everywhere complaining about R.whatever.
Another very useful solution
First create a new package with the desired nameby right clicking on the
java folder -> new -> package.`
Then, select and drag all your classes to the new package. AndroidStudio will re-factor the package name everywhere.
After that: in your app's build.gradle
add/edit applicationId with the new one. i.e. (com.a.bc
in my case):
defaultConfig {
applicationId "com.a.bc"
minSdkVersion 13
targetSdkVersion 19
}
Original post and more comments here
I had one especific issue, i had a Single Page App and needed to show different maps, in diferent divs, one each time. I solved it in not a very beautiful way but a functionally way. Instead of hide the DOM elements with display property i used the visibility property to do it. With this approach Google Maps API had no trouble about know the dimensions of the divs where i had instantiated the maps.
Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.
I saw your edit you could install your headers in default locations usually
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
Confirm with compiler docs though.
PK - Primary Key
NN - Not Null
BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)
UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)
UQ - Create/remove Unique Key
ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )
AI - Auto Increment
G - Generated column. i.e. value generated by a formula based on the other columns
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
If you need more than one condition, so you can try this out
https://www.npmjs.com/package/react-if-elseif-else-render
import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';
class Example extends Component {
render() {
var i = 3; // it will render '<p>Else</p>'
return (
<If condition={i == 1}>
<Then>
<p>Then: 1</p>
</Then>
<ElseIf condition={i == 2}>
<p>ElseIf: 2</p>
</ElseIf>
<Else>
<p>Else</p>
</Else>
</If>
);
}
}
// This is for normal triangle
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
// This is for left triangle, just removed space before printing *
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
If you only want to clear the list box, you should use the Clear (winforms | wpf | asp.net) method:
ListBox2.Items.Clear()
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
You may group your library.available_until wheres area by grouping method of Codeigniter for without disable escaping where clauses.
$this->db
->select('*')
->from('library')
->where('library.rating >=', $form['slider'])
->where('library.votes >=', '1000')
->where('library.language !=', 'German')
->group_start() //this will start grouping
->where('library.available_until >=', date("Y-m-d H:i:s"))
->or_where('library.available_until =', "00-00-00 00:00:00")
->group_end() //this will end grouping
->where('library.release_year >=', $year_start)
->where('library.release_year <=', $year_end)
->join('rating_repo', 'library.id = rating_repo.id')
Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
Yes. You may style any HTML element by its tag name, like this:
select {
font-weight: bold;
}
Of course, you can also use a CSS class to style it, like any other element:
<select class="important">
<option>Important Option</option>
<option>Another Important Option</option>
</select>
<style type="text/css">
.important {
font-weight: bold;
}
</style>
the credit goes for my senior colleague for this:
:> filename
This will not break log files, so you can even use it on syslog, for example.
HxD -- it's a hexeditor, but it allows in place edits, and doesn't barf on large files.
A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.
Don't overuse Vue.component()
, it registers components globally. You can create file, name it MyTask.vue, export there Vue object
https://vuejs.org/v2/guide/single-file-components.html
and then import in your main file, and don't forget to register it:
new Vue({
...
components: { myTask }
...
})
If you have the column and the sequence, you first need to populate a new key for all the existing rows. Assuming you don't care which key is assigned to which row
UPDATE table_name
SET new_pk_column = sequence_name.nextval;
Once that's done, you can create the primary key constraint (this assumes that either there is no existing primary key constraint or that you have already dropped the existing primary key constraint)
ALTER TABLE table_name
ADD CONSTRAINT pk_table_name PRIMARY KEY( new_pk_column )
If you want to generate the key automatically, you'd need to add a trigger
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
:new.new_pk_column := sequence_name.nextval;
END;
If you are on an older version of Oracle, the syntax is a bit more cumbersome
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
SELECT sequence_name.nextval
INTO :new.new_pk_column
FROM dual;
END;
If you are getting following exception:
Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file
Then first check-in all the the directories and then all the files. It will work.
I fixed this error by inserting these lines of code:
<dependency>
<groupId>junit</groupId> <!-- NOT org.junit here -->
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
into <dependencies> node.
more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
Try this
import pandas as pd
data=pd.read_csv('C:/Users/Downloads/winequality-red.csv')
Replace the file target location, with where your data set is found, refer this url https://medium.com/@kanchanardj/jargon-in-python-used-in-data-science-to-laymans-language-part-one-12ddfd31592f
RFC 3066 gives the details of the allowed values (emphasis and links added):
All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.
I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:
Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.
By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.
A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse
):
Type: variant
Subtag: scouse
Description: Scouse
Added: 2006-09-18
Prefix: en
Comments: English Liverpudlian dialect known as 'Scouse'
There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad
(17th century French).
The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:
Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.
I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.
Please try this code:
sorted(glob.glob( os.path.join(path, '*.png') ),key=lambda x:float(re.findall("([0-9]+?)\.png",x)[0]))
There are many options, for example:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))
You can try if/else this shorthand method:
// Syntax
if condition || else condition
// Example
let oldStr = "";
let newStr = oldStr || "Updated Value";
console.log(newStr); // Updated Value
// Example 2
let num1 = 2;
let num2 = num1 || 3;
console.log(num2); // 2 cause num1 is a truthy
@MaxPython The answer above is missing ":"
try:
#do something
except:
# print 'error/exception'
def printError(e): print e
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
Or you can try using git revert http://www.kernel.org/pub/software/scm/git/docs/git-revert.html. I think something like git revert HEAD~1 -m 1
will revert your last commit (if it's still the last commit).
Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.
To get the syntax you asked for, you can implement an "implicit" operator like so:
static implicit operator MyStruct(string s) {
return new MyStruct(...);
}
The implicit operator will work, regardless of whether you make your struct mutable or not.
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks Adnan
Multi purpose function for thread
public enum QueueType {
case Main
case Background
case LowPriority
case HighPriority
var queue: DispatchQueue {
switch self {
case .Main:
return DispatchQueue.main
case .Background:
return DispatchQueue(label: "com.app.queue",
qos: .background,
target: nil)
case .LowPriority:
return DispatchQueue.global(qos: .userInitiated)
case .HighPriority:
return DispatchQueue.global(qos: .userInitiated)
}
}
}
func performOn(_ queueType: QueueType, closure: @escaping () -> Void) {
queueType.queue.async(execute: closure)
}
Use it like :
performOn(.Background) {
//Code
}
You can use reduce
which works in all browser except IE8 and lower.
["20","40","80","400"].reduce(function(a, b) {
return parseInt(a, 10) + parseInt(b, 10);
})
Curl has a built in option for this, called CURLOPT_HEADERFUNCTION. The value of this option must be the name of a callback function. Curl will pass the header (and the header only!) to this callback function, line-by-line (so the function will be called for each header line, starting from the top of the header section). Your callback function then can do anything with it (and must return the number of bytes of the given line). Here is a tested working code:
function HandleHeaderLine( $curl, $header_line ) {
echo "<br>YEAH: ".$header_line; // or do whatever
return strlen($header_line);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
$body = curl_exec($ch);
The above works with everything, different protocols and proxies too, and you dont need to worry about the header size, or set lots of different curl options.
P.S.: To handle the header lines with an object method, do this:
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$object, 'methodName'))
By default Laravel comes with CSRF middleware.
You have 2 options:
I want to do a for loop, yet with askewchan's method it does not work well, so I have modified it.
x = np.empty((0,3))
y = np.array([1,2,3])
for i in ...
x = np.vstack((x,y))
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
You need not to worry
Just enable Jetifier in your projet.
Open gradle.properties
and add below two lines.
android.enableJetifier=true
android.useAndroidX=true
It will convert all support libraries of your dependency to AndroidX at run time (you may have compile time errors, but app will run).
you can see in my example font sizes and background colors are changing according to the screen size
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<style>_x000D_
body {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
/* Custom, iPhone Retina */ _x000D_
@media(max-width:320px){_x000D_
body {_x000D_
background-color: lime;_x000D_
font-size:14px;_x000D_
}_x000D_
}_x000D_
@media only screen and (min-width : 320px) {_x000D_
body {_x000D_
background-color: red;_x000D_
font-size:18px;_x000D_
}_x000D_
}_x000D_
/* Extra Small Devices, Phones */ _x000D_
@media only screen and (min-width : 480px) {_x000D_
body {_x000D_
background-color: aqua;_x000D_
font-size:24px;_x000D_
}_x000D_
}_x000D_
/* Small Devices, Tablets */_x000D_
@media only screen and (min-width : 768px) {_x000D_
body {_x000D_
background-color: green;_x000D_
font-size:30px;_x000D_
}_x000D_
}_x000D_
/* Medium Devices, Desktops */_x000D_
@media only screen and (min-width : 992px) {_x000D_
body {_x000D_
background-color: grey;_x000D_
font-size:34px;_x000D_
}_x000D_
}_x000D_
/* Large Devices, Wide Screens */_x000D_
@media only screen and (min-width : 1200px) {_x000D_
body {_x000D_
background-color: black;_x000D_
font-size:42px;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<p>Resize the browser window. When the width of this document is larger than the height, the background-color is "lightblue", otherwise it is "lightgreen".</p>_x000D_
</body>_x000D_
</html>
_x000D_
If the src is https and the certificate has expired -- and even if you've made an exception -- firefox will still display this error message, and you can see the exact reason why if you look at the request under the network tab.
GoDaddy shared server solution
I had the same issue when trying to deploy separate Laravel project on a subdomain level.
File structure
- public_html (where the main web app resides)
[works fine]
- booking.mydomain.com (folder for separate Laravel project)
[showing error 403 forbidden]
Solution
go to cPanel of your GoDaddy account
open File Manager
browse to the folder that shows 403 forbidden error
in the File Manager, right-click on the folder (in my case booking.mydomain.com)
select Change Permissions
select following checkboxes
a) user - read, write, execute
b) group - read, execute
c) world - read, execute
Permission code must display as 755
Click change permissions
Here is what I do to avoid the issues of making the remote server accept your local external IP:
-L
to transfer the port 6006
of the remote server into the port 16006
of my machine (for instance):
ssh -L 16006:127.0.0.1:6006 olivier@my_server_ip
What it does is that everything on the port 6006
of the server (in 127.0.0.1:6006
) will be forwarded to my machine on the port 16006
.
tensorboard --logdir log
with the default 6006
portI had a similar problem. And i had to make it install the same way, we do from pypi.
I did the following things:
Make a directory to store all the packages in the machine that have internet access.
mkdir -p /path/to/packages/
Download all the packages to the path
Edit: You can also try:
python3 -m pip wheel --no-cache-dir -r requirements.txt -w /path/to/packages
pip download -r requirements.txt -d /path/to/packages
Eg:- ls /root/wheelhouse/ # **/root/wheelhouse** is my **/path/to/packages/**
total 4524
-rw-r--r--. 1 root root 16667 May 23 2017 incremental-17.5.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 34713 Sep 1 10:21 attrs-18.2.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 3088398 Oct 15 14:41 Twisted-18.9.0.tar.bz2
-rw-r--r--. 1 root root 133356 Jan 28 15:58 chardet-3.0.4-py2.py3-none-any.whl
-rw-r--r--. 1 root root 154154 Jan 28 15:58 certifi-2018.11.29-py2.py3-none-any.whl
-rw-r--r--. 1 root root 57987 Jan 28 15:58 requests-2.21.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 58594 Jan 28 15:58 idna-2.8-py2.py3-none-any.whl
-rw-r--r--. 1 root root 118086 Jan 28 15:59 urllib3-1.24.1-py2.py3-none-any.whl
-rw-r--r--. 1 root root 47229 Jan 28 15:59 tqdm-4.30.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 7922 Jan 28 16:13 constantly-15.1.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 164706 Jan 28 16:14 zope.interface-4.6.0-cp27-cp27mu-manylinux1_x86_64.whl
-rw-r--r--. 1 root root 573841 Jan 28 16:14 setuptools-40.7.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 37638 Jan 28 16:15 Automat-0.7.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 37905 Jan 28 16:15 hyperlink-18.0.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 52311 Jan 28 16:15 PyHamcrest-1.9.0-py2.py3-none-any.whl
-rw-r--r--. 1 root root 10586 Jan 28 16:15 six-1.12.0-py2.py3-none-any.whl
Tar the packages directory and copy it to the Machine that doesn't have internet access. Then do,
cd /path/to/packages/
tar -cvzf packages.tar.gz . # not the . (dot) at the end
Copy the packages.tar.gz into the destination machine that doesn't have internet access.
In the machine that doesn't have internet access, do the following (Assuming you copied the tarred packages to /path/to/package/ in the current machine)
cd /path/to/packages/
tar -xvzf packages.tar.gz
mkdir -p $HOME/.config/pip/
vi $HOME/.config/pip/pip.conf
and paste the following content inside and save it.
[global]
timeout = 10
find-links = file:///path/to/package/
no-cache-dir = true
no-index = true
Finally, i suggest you use, some form of virtualenv
for installing the packages.
virtualenv -p python2 venv # use python3, if you are on python3
source ./venv/bin/activate
pip install <package>
You should be able to download all the modules that are in the directory /path/to/package/.
Note: I only did this, because i couldn't add options or change the way we install the modules. Otherwise i'd have done
pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt
The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.
To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse
dtResult.Rows(i)("Foo") = strVerse
Working for me with this line (simply add --listen when running) :
node server.js -p 3000 -a : --listen 192.168.1.100
Hope it helps...
code from google analytics ga.js
function c(a){
var d=[],
e=document.cookie.split(";");
a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
for(var b=0;b<e.length;b++){
var f=e[b].match(a);
f&&d.push(f[1])
}
return d
}
Play around this piece of code. Focus on the concept, edit where necessary so that it can
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
Delegate update form </p>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link href='http://fonts.googleapis.com/css?family=Droid+Serif|Ubuntu' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="js/flexslider/flexslider.css" />
<link rel="stylesheet" href="css/basic-style.css">
<script src="js/libs/modernizr-2.6.2.min.js"></script>
</head>
<body id="home">
<header class="wrapper clearfix">
<nav id="topnav" role="navigation">
<div class="menu-toggle">Menu</div>
<ul class="srt-menu" id="menu-main-navigation">
<li><a href="Swift_Landing.html">Home page</a></li>
</header>
</section>
<style>
form label {
display: inline-block;
width: 100px;
font-weight: bold;
}
</style>
</ul>
<?php
session_start();
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
$Username=$_SESSION['myssession'];
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='$Username'";
$result = mysql_query ($sql) or die (mysql_error ());
while ($row = mysql_fetch_array ($result)){
?>
<form action="Delegate_update.php" method="post">
Name
<input type="text" name="Namex" value="<?php echo $row ['Name']; ?> " size=10>
Username
<input type="text" name="Username" value="<?php echo $row ['User_name']; ?> " size=10>
Password
<input type="text" name="Password" value="<?php echo $row ['User_password']; ?>" size=17>
<input type="submit" name="submit" value="Update">
</form>
<?php
}
?>
</p>
</body>
</html>
Short Summary
Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
Long Answer
Firstly, one needs to know what's Directory Service
.
Directory Service is a software system that stores, organises, and provides access to information in a computer operating system's directory. In software engineering, a directory is a map between names and values. It allows the lookup of named values, similar to a dictionary.
For more details, read https://en.wikipedia.org/wiki/Directory_service
Secondly,as one could imagine, different vendors implement all kinds of forms of directory service, which is harmful to multi-vendor interoperability.
Thirdly, so in the 1980s, the ITU and ISO came up with a set of standards - X.500, for directory services, initially to support the requirements of inter-carrier electronic messaging and network name lookup.
Fourthly, so based on this standard, Lightweight Directory Access Protocol, LDAP, is developed. It uses the TCP/IP stack and a string encoding scheme of the X.500 Directory Access Protocol (DAP), giving it more relevance on the Internet.
Lastly, based on this LDAP/X.500 stack, Microsoft implemented a modern directory service for Windows, originating from the X.500 directory, created for use in Exchange Server. And this implementation is called Active Directory
.
So in a short summary, Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
PS[0]: This answer heavily copies content from the wikipedia page listed above.
PS[1]: To know why it may be better use directory service rather just using a relational database, read https://en.wikipedia.org/wiki/Directory_service#Comparison_with_relational_databases
Here is the same function that @BrunoLM posted converted to a String prototype function:
String.prototype.getBytes = function () {
var bytes = [];
for (var i = 0; i < this.length; ++i) {
bytes.push(this.charCodeAt(i));
}
return bytes;
};
If you define the function as such, then you can call the .getBytes() method on any string:
var str = "Hello World!";
var bytes = str.getBytes();
This code doesn't do what you expect:
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
If you pass an empty string (""
) or vbNullString
to Dir
, it will return the name of the first file in the current directory path (the path returned by CurDir$
). So, if SigString
is empty, your If
condition will evaluate to True
because Dir
will return a non-empty string (the name of the first file in the current directory), and GetBoiler
will be called. And if SigString
is empty, the call to fso.GetFile
will fail.
You should either change your condition to check that SigString
isn't empty, or use the FileSystemObject.FileExists
method instead of Dir
for checking if the file exists. Dir
is tricky to use precisely because it does things you might not expect it to do. Personally, I would use Scripting.FileSystemObject
over Dir
because there's no funny business (FileExists
returns True
if the file exists, and, well, False
if it doesn't). What's more, FileExists
expresses the intent of your code much clearly than Dir
.
Method 1: Check that SigString
is non-empty first
If SigString <> "" And Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
Method 2: Use the FileSystemObject.FileExists
method
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(SigString) Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
something like this? http://codepen.io/Nunotmp/pen/wKjvB
You can add an empty div
and use absolute positioning.
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.
Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.
Internally, hash()
method calls __hash__()
method of an object which are set by default for any object.
>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,
>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])
>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506
The solution to avoid this error is to restructure the list to have nested tuples instead of lists.
It looks like all of the edits are already a part of the index. So to commit just use the commit
command
git commit -m "My Commit Message"
Looking at your messages though my instinct says that you probably don't want the cache
files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file
httpdocs/newsite/manifest/cache/*
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
By default, oracle date subtraction returns a result in # of days.
So just multiply by 24 to get # of hours, and again by 60 for # of minutes.
Example:
select
round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
(
select
to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
from
dual
) test_data
There are multiple possible causes for this error:
1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input()
decorator
Your html file:
<body [x]="...">
Your class file:
export class YourComponentClass {
@Input()
x: string;
...
}
(make sure you also have the parentheses)
2) Make sure you registered your component/directive/pipe classes in NgModule:
@NgModule({
...
declarations: [
...,
YourComponentClass
],
...
})
See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.
3) Also happens if you have a typo in your angular directive. For example:
<div *ngif="...">
^^^^^
Instead of:
<div *ngIf="...">
This happens because under the hood angular converts the asterisk syntax to:
<div [ngIf]="...">
If you want the actual strings themselves to mutate in place (possibly and desirably affecting other references to the same string objects):
# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |_,str| str.gsub! /^|$/, '%' }
my_hash.each{ |_,str| str.replace "%#{str}%" }
If you want the hash to change in place, but you don't want to affect the strings (you want it to get new strings):
# Two ways to achieve the same result (any Ruby version)
my_hash.each{ |key,str| my_hash[key] = "%#{str}%" }
my_hash.inject(my_hash){ |h,(k,str)| h[k]="%#{str}%"; h }
If you want a new hash:
# Ruby 1.8.6+
new_hash = Hash[*my_hash.map{|k,str| [k,"%#{str}%"] }.flatten]
# Ruby 1.8.7+
new_hash = Hash[my_hash.map{|k,str| [k,"%#{str}%"] } ]
>>> range(6, 0, -1)
[6, 5, 4, 3, 2, 1]
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
As of PowerShell 2, simple:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit
to force case-sensitivity. See about_Split for more details.
You can use std::numeric_limits
which is defined in <limits>
to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a -
in front for negative infinity).
#include <limits>
//...
std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();
As noted in the comments, min()
returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.
There is of course the std::max_element
and min_element functions (defined in <algorithm>
) which may be a better choice for finding the largest or smallest value in an array.
add "MainContent_" to ID value!
Example: (Error)
document.getElementById("Password").value = text;
(ok!)
document.getElementById("**MainContent_**Password").value = text;
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
I had same issue after installing nvm-windows
on top of existing Node installation. Solution was just to follow the instructions:
You should also delete the existing npm install location (e.g. "C:\Users\AppData\Roaming\npm") so that the nvm install location will be correctly used instead.
To close this question, what seemed to have worked is indeed running
docker-compose stop
docker-compose rm -f
docker-compose -f docker-compose.yml up -d
I.e. remove the containers before running up
again.
What one needs to keep in mind when doing it like this is that data volume containers are removed as well if you just run rm -f
. In order to prevent that I specify explicitly each container to remove:
docker-compose rm -f application nginx php
As I said in my question, I don't know if this is the correct process. But this seems to work for our use case, so until we find a better solution we'll roll with this one.
one
has not been assigned so points to an unpredictable location. You should either place it on the stack:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of free
in this case. In general, you'll need exactly one call to free
for each call made to malloc
.
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi