You can use default javascript cookies set method. this working perfect.
createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
let date = new Date();
date.setTime(date.getTime()+(hourToExpire*60*60*1000));
document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},
call java scripts funtion in react method as below,
createCookieInHour('cookieName', 'cookieValue', 5);
and you can use below way to view cookies.
let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);
please refer below document for more information - URL
Until 24 hrs.
As Duration.format
is deprecated, with [email protected]
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');
Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.
So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.
import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack
first_link.send_keys(Keys.CONTROL + Keys.RETURN)
# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.quit()
I think this is better solution so far.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
Based on this answer and this answer. I've created a public gist
How it can be used
let boolean: Bool = UIDevice.isDevice(ofType: .iPhoneX)
// true or false
let specificDevice: DeviceModel.Model = UIDevice.modelType
// iPhone6s, iPhoneX, iPad etc...
let model: DeviceModel = UIDevice.model
// .simulator(let specificDevice), .real(let specificDevice),
// .unrecognizedSimulator(let string), .unrecognized(let string)
let modelName: String = UIDevice.model.name
// iPhone 6, iPhone X, etc...
This is the code inside the gist
public extension UIDevice {
public static var modelCode: String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
}
public static var model: DeviceModel {
// Thanks https://stackoverflow.com/a/26962452/5928180
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
// Thanks https://stackoverflow.com/a/33495869/5928180
if modelCode == "i386" || modelCode == "x86_64" {
if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"], let model = DeviceModel.Model(modelCode: simulatorModelCode) {
return DeviceModel.simulator(model)
} else if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
return DeviceModel.unrecognizedSimulator(simulatorModelCode)
} else {
return DeviceModel.unrecognized(modelCode)
}
} else if let model = DeviceModel.Model(modelCode: modelCode) {
return DeviceModel.real(model)
} else {
return DeviceModel.unrecognized(modelCode)
}
}
public static var modelType: DeviceModel.Model? {
return UIDevice.model.model
}
public static func isDevice(ofType model: DeviceModel.Model) -> Bool {
return UIDevice.modelType == model
}
}
public enum DeviceModel {
case simulator(Model)
case unrecognizedSimulator(String)
case real(Model)
case unrecognized(String)
public enum Model: String {
case iPod1 = "iPod 1"
case iPod2 = "iPod 2"
case iPod3 = "iPod 3"
case iPod4 = "iPod 4"
case iPod5 = "iPod 5"
case iPad2 = "iPad 2"
case iPad3 = "iPad 3"
case iPad4 = "iPad 4"
case iPhone4 = "iPhone 4"
case iPhone4S = "iPhone 4S"
case iPhone5 = "iPhone 5"
case iPhone5S = "iPhone 5S"
case iPhone5C = "iPhone 5C"
case iPadMini1 = "iPad Mini 1"
case iPadMini2 = "iPad Mini 2"
case iPadMini3 = "iPad Mini 3"
case iPadAir1 = "iPad Air 1"
case iPadAir2 = "iPad Air 2"
case iPadPro9_7 = "iPad Pro 9.7\""
case iPadPro9_7_cell = "iPad Pro 9.7\" cellular"
case iPadPro10_5 = "iPad Pro 10.5\""
case iPadPro10_5_cell = "iPad Pro 10.5\" cellular"
case iPadPro12_9 = "iPad Pro 12.9\""
case iPadPro12_9_cell = "iPad Pro 12.9\" cellular"
case iPhone6 = "iPhone 6"
case iPhone6plus = "iPhone 6 Plus"
case iPhone6S = "iPhone 6S"
case iPhone6Splus = "iPhone 6S Plus"
case iPhoneSE = "iPhone SE"
case iPhone7 = "iPhone 7"
case iPhone7plus = "iPhone 7 Plus"
case iPhone8 = "iPhone 8"
case iPhone8plus = "iPhone 8 Plus"
case iPhoneX = "iPhone X"
init?(modelCode: String) {
switch modelCode {
case "iPod1,1": self = .iPod1
case "iPod2,1": self = .iPod2
case "iPod3,1": self = .iPod3
case "iPod4,1": self = .iPod4
case "iPod5,1": self = .iPod5
case "iPad2,1": self = .iPad2
case "iPad2,2": self = .iPad2
case "iPad2,3": self = .iPad2
case "iPad2,4": self = .iPad2
case "iPad2,5": self = .iPadMini1
case "iPad2,6": self = .iPadMini1
case "iPad2,7": self = .iPadMini1
case "iPhone3,1": self = .iPhone4
case "iPhone3,2": self = .iPhone4
case "iPhone3,3": self = .iPhone4
case "iPhone4,1": self = .iPhone4S
case "iPhone5,1": self = .iPhone5
case "iPhone5,2": self = .iPhone5
case "iPhone5,3": self = .iPhone5C
case "iPhone5,4": self = .iPhone5C
case "iPad3,1": self = .iPad3
case "iPad3,2": self = .iPad3
case "iPad3,3": self = .iPad3
case "iPad3,4": self = .iPad4
case "iPad3,5": self = .iPad4
case "iPad3,6": self = .iPad4
case "iPhone6,1": self = .iPhone5S
case "iPhone6,2": self = .iPhone5S
case "iPad4,1": self = .iPadAir1
case "iPad4,2": self = .iPadAir2
case "iPad4,4": self = .iPadMini2
case "iPad4,5": self = .iPadMini2
case "iPad4,6": self = .iPadMini2
case "iPad4,7": self = .iPadMini3
case "iPad4,8": self = .iPadMini3
case "iPad4,9": self = .iPadMini3
case "iPad6,3": self = .iPadPro9_7
case "iPad6,11": self = .iPadPro9_7
case "iPad6,4": self = .iPadPro9_7_cell
case "iPad6,12": self = .iPadPro9_7_cell
case "iPad6,7": self = .iPadPro12_9
case "iPad6,8": self = .iPadPro12_9_cell
case "iPad7,3": self = .iPadPro10_5
case "iPad7,4": self = .iPadPro10_5_cell
case "iPhone7,1": self = .iPhone6plus
case "iPhone7,2": self = .iPhone6
case "iPhone8,1": self = .iPhone6S
case "iPhone8,2": self = .iPhone6Splus
case "iPhone8,4": self = .iPhoneSE
case "iPhone9,1": self = .iPhone7
case "iPhone9,2": self = .iPhone7plus
case "iPhone9,3": self = .iPhone7
case "iPhone9,4": self = .iPhone7plus
case "iPhone10,1": self = .iPhone8
case "iPhone10,2": self = .iPhone8plus
case "iPhone10,3": self = .iPhoneX
case "iPhone10,6": self = .iPhoneX
default: return nil
}
}
}
public var name: String {
switch self {
case .simulator(let model): return "Simulator[\(model.rawValue)]"
case .unrecognizedSimulator(let s): return "UnrecognizedSimulator[\(s)]"
case .real(let model): return model.rawValue
case .unrecognized(let s): return "Unrecognized[\(s)]"
}
}
public var model: DeviceModel.Model? {
switch self {
case .simulator(let model): return model
case .real(let model): return model
case .unrecognizedSimulator(_): return nil
case .unrecognized(_): return nil
}
}
}
As said in the comments, the problem lies in your script. Actually, there are 2 problems:
None
somewhere. Maybe due to the defaultdict ?show()
after each subplot. show()
should be called once at the end of your script. The alternative is to use interactive mode, look for ion
in matplotlib's documentation.This works for me
# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes
The SettingWithCopyWarning
was created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.]
df[df['A'] > 2]['B'] = new_val # new_val not set in df
The warning offers a suggestion to rewrite as follows:
df.loc[df['A'] > 2, 'B'] = new_val
However, this doesn't fit your usage, which is equivalent to:
df = df[df['A'] > 2]
df['B'] = new_val
While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the docs on indexing, if you'd like to read further. You can safely disable this new warning with the following assignment.
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
This function can handle objects containing both objects and arrays of objects. Result will be one line per each single item of the object, representing its full path in the structure.
Tested with http://haya2now.jp/data/data.json
Example result: geometry[6].obs[5].hayabusa2.delay_from
function iterate(obj, stack, prevType) {
for (var property in obj) {
if ( Array.isArray(obj[property]) ) {
//console.log(property , "(L=" + obj[property].length + ") is an array with parent ", prevType, stack);
iterate(obj[property], stack + property , "array");
} else {
if ((typeof obj[property] != "string") && (typeof obj[property] != "number")) {
if(prevType == "array") {
//console.log(stack + "[" + property + "] is an object, item of " , prevType, stack);
iterate(obj[property], stack + "[" +property + "]." , "object");
} else {
//console.log(stack + property , "is " , typeof obj[property] , " with parent ", prevType, stack );
iterate(obj[property], stack + property + ".", "object");
}
} else {
if(prevType == "array") {
console.log(stack + "[" + property + "] = "+ obj[property]);
} else {
console.log(stack + property , " = " , obj[property] );
}
}
}
}
}
iterate(object, '', "File")
console.log(object);
Note that const declarations are block-scoped.
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
So the value of definitelyAnElement is not accessible outside of the {}.
(I would have commented above, but I do not have enough Reputation apparently.)
Your header file Hash.h
declares "what class hash
should look like", but not its implementation, which is (presumably) in some other source file we'll call Hash.cpp
. By including the header in your main file, the compiler is informed of the description of class Hash
when compiling the file, but not how class Hash
actually works. When the linker tries to create the entire program, it then complains that the implementation (toHash::insert(int, char)
) cannot be found.
The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:
g++ -o main Hash.cpp main.cpp
will create the main program called "main".
For this thing you can use @property
as an decorator, so you could use instance methods as attributes. For example:
class Word_Parser:
def __init__(self, sentences):
self.sentences = sentences
@property
def parser(self):
self.word_list = self.sentences.split()
@property
def sort_word_list(self):
self.sorted_word_list = self.word_list.sort()
@property
def num_words(self):
self.num_words = len(self.word_list)
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words
so you can use access the attributes without calling (i.e., without the ()
).
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
.c_str()
returns a const char*
. If you need a mutable version, you will need to produce a copy yourself.
For me it helped to enable the automated discovery in Properties -> C/C++-Build -> Discovery Options to resolve this problem.
umh.. like that?
$newstring = substr($dynamicstring, -7);
Put your script in a file foo.py
starting with
#!/usr/bin/python
Then give execute permission to that script using
chmod a+x foo.py
and use the full path of your foo.py
file in your crontab
.
See documentation of execve(2) which is handling the shebang.
No, you'll need to do it manually.
function prettyDate(date) {_x000D_
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(1324339200000)));
_x000D_
Ctrl + Shift + P
Then type and click on > preferences:configure language specific settings
and then type "python" after that. Paste the code
{
"python.linting.pylintArgs": [
"--load-plugins=pylint_django", "--errors-only"
],
}
http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Yes, You can use gcc to compile your asm code. Use -c for compilation like this:
gcc -c file.S -o file.o
This will give object code file named file.o. To invoke linker perform following after above command:
gcc file.o -o file
You could also do this
#include <comdef.h>
BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
or std::string if you prefer
EDIT: if your original string contains multiple embedded \0 this approach will not work.
I found that I needed to wrap my datetime string like this:
"startdate": "\/Date(" + date() + ")\/"
Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD
I attended a coursera course, there was lesson in which, we were taught about design recipe.
Below docstring format I found preety useful.
def area(base, height): '''(number, number ) -> number #**TypeContract** Return the area of a tring with dimensions base #**Description** and height >>>area(10,5) #**Example ** 25.0 >>area(2.5,3) 3.75 ''' return (base * height) /2
I think if docstrings are written in this way, it might help a lot to developers.
Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI
@Amjad, good idea, but a better implementation would be:
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}
I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.
pep257 will report divergence you make from the standard and is called like pylint and pep8.
To quote the specifications:
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's
__init__.py
module) should also list the modules and subpackages exported by the package.The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its
__init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
When you say:
#include <cstring>
the g++ compiler should put the <string.h>
declarations it itself includes into the std::
AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy
with std::strcpy
and see if that fixes the problem.
strToLower should return a char * instead of a char. Something like this would do.
char *strToLower(char *cString)
You could use a colormap such as HSV to generate a set of colors. For example:
cc=hsv(12);
figure;
hold on;
for i=1:12
plot([0 1],[0 i],'color',cc(i,:));
end
MATLAB has 13 different named colormaps ('doc colormap' lists them all).
Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.
All boils down to if your server backend is timezone-agnostic or not. If it is not, then you need to assume that timezone of server is the same as client, or transfer information about client's timezone and include that also into calculations.
a PostgreSQL backend based example:
select '2009-09-28T08:00:00Z'::timestamp -> '2009-09-28 08:00:00' (wrong for 10am)
select '2009-09-28T08:00:00Z'::timestamptz -> '2009-09-28 10:00:00+02'
select '2009-09-28T08:00:00Z'::timestamptz::timestamp -> '2009-09-28 10:00:00'
The last one is probably what you want to use in database, if you are not willing properly implement timezone logic.
it pretty much depends on the relative sizes of the new string after every new concatenation.
With the +
operator, for every concatenation a new string is made. If the intermediary strings are relatively long, the +
becomes increasingly slower because the new intermediary string is being stored.
Consider this case:
from time import time
stri=''
a='aagsdfghfhdyjddtyjdhmfghmfgsdgsdfgsdfsdfsdfsdfsdfsdfddsksarigqeirnvgsdfsdgfsdfgfg'
l=[]
#case 1
t=time()
for i in range(1000):
stri=stri+a+repr(i)
print time()-t
#case 2
t=time()
for i in xrange(1000):
l.append(a+repr(i))
z=''.join(l)
print time()-t
#case 3
t=time()
for i in range(1000):
stri=stri+repr(i)
print time()-t
#case 4
t=time()
for i in xrange(1000):
l.append(repr(i))
z=''.join(l)
print time()-t
Results
1 0.00493192672729
2 0.000509023666382
3 0.00042200088501
4 0.000482797622681
In the case of 1&2, we add a large string, and join() performs about 10 times faster. In case 3&4, we add a small string, and '+' performs slightly faster
I like the fundamental differences in the way that Ruby and Python method invocations operate.
Ruby methods are invoked via a form "message passing" and need not be explicitly first-class functions (there are ways to lift methods into "proper" function-objects) -- in this aspect Ruby is similar to Smalltalk.
Python works much more like JavaScript (or even Perl) where methods are functions which are invoked directly (there is also stored context information, but...)
While this might seem like a "minor" detail it is really just the surface of how different the Ruby and Python designs are. (On the other hand, they are also quite the same :-)
One practical difference is the concept of method_missing
in Ruby (which, for better or worse, seems to be used in some popular frameworks). In Python, one can (at least partially) emulate the behavior using __getattr__/__getattribute__, albeit non-idiomatically.
Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
int atoi(
const char *str
);
int _wtoi(
const wchar_t *str
);
int _atoi_l(
const char *str,
_locale_t locale
);
int _wtoi_l(
const wchar_t *str,
_locale_t locale
);
CString is wchar_t string. So, if you want convert Cstring to int, you can use:
CString s;
int test = _wtoi(s)
Generic Conversion Macros (TN059 Other Considerations section is important):
A2CW (LPCSTR) -> (LPCWSTR)
A2W (LPCSTR) -> (LPWSTR)
W2CA (LPCWSTR) -> (LPCSTR)
W2A (LPCWSTR) -> (LPSTR)
Interactively, you can display it with
help(my_func)
Or from code you can retrieve it with
my_func.__doc__
This is an article that I always refer to when working with sockets..
It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.
If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio
are imho quite complicated when it comes to short and simple "hello world" example.
To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm
Add following includes to both files:
#include <cstdlib>
#include <cstring>
#include <unistd.h>
In client.c, change the line:
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
to:
if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
As you can see in C++ an explicit cast is needed.
You can do objects the JavaScript way... It makes no sense but it works ;)
>>> def FakeObject():
... def test():
... print "foo"
... FakeObject.test = test
... return FakeObject
>>> x = FakeObject()
>>> x.test()
foo
from this post (Thank you Mark Ransom )
Convert CString to string (VC6)
I have tested this and it works fine.
std::string Utils::CString2String(const CString& cString)
{
std::string strStd;
for (int i = 0; i < cString.GetLength(); ++i)
{
if (cString[i] <= 0x7f)
strStd.append(1, static_cast<char>(cString[i]));
else
strStd.append(1, '?');
}
return strStd;
}
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
I have adopted the practice of putting all imports in the functions that use them, rather than at the top of the module.
The benefit I get is the ability to refactor more reliably. When I move a function from one module to another, I know that the function will continue to work with all of its legacy of testing intact. If I have my imports at the top of the module, when I move a function, I find that I end up spending a lot of time getting the new module's imports complete and minimal. A refactoring IDE might make this irrelevant.
There is a speed penalty as mentioned elsewhere. I have measured this in my application and found it to be insignificant for my purposes.
It is also nice to be able to see all module dependencies up front without resorting to search (e.g. grep). However, the reason I care about module dependencies is generally because I'm installing, refactoring, or moving an entire system comprising multiple files, not just a single module. In that case, I'm going to perform a global search anyway to make sure I have the system-level dependencies. So I have not found global imports to aid my understanding of a system in practice.
I usually put the import of sys
inside the if __name__=='__main__'
check and then pass arguments (like sys.argv[1:]
) to a main()
function. This allows me to use main
in a context where sys
has not been imported.
You can easily transpose an array with zip.
a = [(1,2), (3,4), (5,6)]
zip(*a)
# [(1, 3, 5), (2, 4, 6)]
Per @EthanB suggestion and @karim making a back filled rectangle, I just created a category for the UIButton to achieve this.
Just drop in the Category code: https://github.com/zmonteca/UIButton-PLColor
Usage:
[button setBackgroundColor:uiTextColor forState:UIControlStateDisabled];
Optional forStates to use:
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
Copying from this answer: https://stackoverflow.com/a/56766138/11502722
I was able to get this somewhat working for C++ static_assert()
. The wrinkle here is that static_assert()
only accepts string literals; constexpr string_view
will not work. You will need to accept extra text around the typename, but it works:
template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
}
}
MSVC Output:
error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...
Get the Sothink SWF decompiler. Not free, but worth it. Recently used it to decompile an SWF that I had lost the fla for, and I could completely round-trip swf-fla and back!
link text
I tried using Google reCAPTCHA explicitly. Here is the example:
// put somewhere in your index.html
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('your-recaptcha-element', {
'sitekey' : '6Ldcfv8SAAAAAB1DwJTM6T7qcJhVqhqtss_HzS3z'
});
};
//link function of Angularjs directive
link: function (scope, element, attrs) {
...
var domElem = '<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>';
$('#your-recaptcha-element').append($compile(domElem)(scope));
}
$('#message').val('');
Explanation (from @BalusC):
textarea
is an input
element with a value. You actually want to "empty" the value. So as for every other input
element (input
, select
, textarea
) you need to use element.val('');
.
Also see docs
Try using:
xattr -rd com.apple.quarantine directoryname
This takes care of recursively removing the pesky attribute everywhere.
Below is the way to crop an image.
image_path: The path to the image to edit
coords: A tuple of x/y coordinates (x1, y1, x2, y2)[open the image in mspaint and check the "ruler" in view tab to see the coordinates]
saved_location: Path to save the cropped image
from PIL import Image
def crop(image_path, coords, saved_location:
image_obj = Image.open("Path of the image to be cropped")
cropped_image = image_obj.crop(coords)
cropped_image.save(saved_location)
cropped_image.show()
if __name__ == '__main__':
image = "image.jpg"
crop(image, (100, 210, 710,380 ), 'cropped.jpg')
That is because you are opening , writing and closing the file 10 times inside your for loop
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
You should open and close your file outside for loop.
myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
myfile.write("%s\n" % var1)
myfile.close()
text_file.close()
You should also notice to use write and not writelines.
writelines
writes a list of lines to your file.
Also you should check out the answers posted by folks here that uses with
statement. That is the elegant way to do file read/write operations in Python
When rebase or push to head/master this error may occurred
remote: GitLab: You are not allowed to access some of the refs!
To git@giturl:main/xyz.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@giturl:main/xyz.git'
To resolve this issue in git dashboard should remove master branch from "Protected branches"
then you can run this command
git push -f origin master
or
git rebase --onto temp $1 master
I find this approach a bit more flexible, here you just providing generator function that emits key, value pairs and can be easily extended to also iterate over lists.
def traverse(value, key=None):
if isinstance(value, dict):
for k, v in value.items():
yield from traverse(v, k)
else:
yield key, value
Then you can write your own myprint
function, then would print those key value pairs.
def myprint(d):
for k, v in traverse(d):
print(f"{k} : {v}")
A test:
myprint({
'xml': {
'config': {
'portstatus': {
'status': 'good',
},
'target': '1',
},
'port': '11',
},
})
Output:
status : good
target : 1
port : 11
I tested this on Python 3.6.
The single " | " operator will evaluate both sides of the expression.
if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
// Do stuff here
}
The double operator " || " will only evaluate the left side if the expression returns true.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
C# has many similarities to C++ but their still are differences between the two languages ;)
In C, you don't need to cast the return value of malloc
. The pointer to void returned by malloc
is automagically converted to the correct type. However, if you want your code to compile with a C++ compiler, a cast is needed. A preferred alternative among the community is to use the following:
int *sieve = malloc(sizeof *sieve * length);
which additionally frees you from having to worry about changing the right-hand side of the expression if ever you change the type of sieve
.
Casts are bad, as people have pointed out. Especially pointer casts.
iter->first
and iter->second
are variables, you are attempting to call them as methods.
Paste the following at the top of your JavaScript (before using the console):
/**
* Protect window.console method calls, e.g. console is not defined on IE
* unless dev tools are open, and IE doesn't define console.debug
*
* Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
* Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
* Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
* Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
* Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
*/
(function() {
// Union of Chrome, Firefox, IE, Opera, and Safari console methods
var methods = ["assert", "cd", "clear", "count", "countReset",
"debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
"groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
"select", "table", "time", "timeEnd", "timeStamp", "timeline",
"timelineEnd", "trace", "warn"];
var length = methods.length;
var console = (window.console = window.console || {});
var method;
var noop = function() {};
while (length--) {
method = methods[length];
// define undefined methods as noops to prevent errors
if (!console[method])
console[method] = noop;
}
})();
The function closure wrapper is to scope the variables as to not define any variables. This guards against both undefined console
and undefined console.debug
(and other missing methods).
EDIT: I noticed that HTML5 Boilerplate uses similar code in its js/plugins.js file, if you're looking for a solution that will (probably) be kept up-to-date.
You are mixing pointers and arrays. If what you want is an array, then use an array:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
<system.webServer>
<staticContent>
<remove fileExtension=".woff"/>
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
</staticContent>
</system.webServer>
This is for windows:
For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".
@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal
This script is located in "mygrapher". To run things, I would get into my command prompt, then do:
>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)
You may get ORA-01031: insufficient privileges
instead of ORA-00942: table or view does not exist
when you have at least one privilege on the table, but not the necessary privilege.
Create schemas
SQL> create user schemaA identified by schemaA;
User created.
SQL> create user schemaB identified by schemaB;
User created.
SQL> create user test_user identified by test_user;
User created.
SQL> grant connect to test_user;
Grant succeeded.
Create objects and privileges
It is unusual, but possible, to grant a schema a privilege like DELETE without granting SELECT.
SQL> create table schemaA.table1(a number);
Table created.
SQL> create table schemaB.table2(a number);
Table created.
SQL> grant delete on schemaB.table2 to test_user;
Grant succeeded.
Connect as TEST_USER and try to query the tables
This shows that having some privilege on the table changes the error message.
SQL> select * from schemaA.table1;
select * from schemaA.table1
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select * from schemaB.table2;
select * from schemaB.table2
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL>
There is a good solution to this issue:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class);
Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);
Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.
Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();
BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);
BigDecimal revenue = results.getResult().get(0).getRevenue();
Simply do it
sudo apt install php-mysqli
It works perfectly and it is version independent
Using the selectedOptions
property:
var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);
It works in all browsers except Internet Explorer.
This:
SELECT col1 as a,
CASE WHEN a = 'test' THEN 'yes' END as value
FROM table;
...will not work. This will:
SELECT CASE WHEN a = 'test' THEN 'yes' END as value
FROM (SELECT col1 AS a
FROM TABLE)
Why you wouldn't use:
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
...I don't know.
A bit more readable comparing is done by casting event.key
to upper case (I used onkeyup - needed the event to fire once upon each key tap):
window.onkeyup = function(event) {
let key = event.key.toUpperCase();
if ( key == 'W' ) {
// 'W' key is pressed
} else if ( key == 'D' ) {
// 'D' key is pressed
}
}
Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))
I usually open them with 7-Zip... It allows at least to see packages and classes and resources.
Should I need to see methods or fields, I would use Jad but of course, it is better to rely on (good) JavaDoc...
Now, somewhere on SO was mentioned some Eclipse plug-ins, to find in which jar file a class is located, perhaps they can do more (ie. what you requested).
[EDIT] Reference to SO thread. Not what is asked, but somehow related, thus useful: Java: How do I know which jar file to use given a class name?
For Python2.7 - modifying MYGz's answer to not strip milliseconds:
from datetime import datetime
d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)
print(datetime.fromtimestamp(float(d)))
Output:
1482248322760
2016-12-20 09:38:42.760000
This is a great help. The code
UPDATE tbl_b b
SET ( column1, column2, column3)
= (a.column1, a.column2, a.column3)
FROM tbl_a a
WHERE b.id = 1
AND a.id = b.id;
works perfectly.
noted that you need a bracket "" in
From "tbl_a" a
to make it work.
Working example in php.
First Alert then Redirect works....
Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
This one command workes for me (Suse):
mail-srv:/var/log # tail -f /var/log/mail.info |grep --line-buffered LOGIN >> logins_to_mail
collecting logins to mail service
If your requirements are to have no duplicates, you should be using a HashSet.
HashSet.Add will return false when the item already exists (if that even matters to you).
You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice
(GetHashCode
& Equals
).
Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:
<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>
You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:
<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->
you can use BCP in and out for small tables.
BCP OUT command:-
BCP "SELECT * FROM [Dinesh].[dbo].[Invoices]" QUERYOUT C:\av\Invoices1.txt -S MC0XENTC -T -c -r c:\error.csv
BCP IN command:- Create table structure for Invoicescopy1.
BCP [Dinesh].[dbo].[Invoicescopy1] IN C:\av\Invoices.txt -S MC0XENTC -T -c
If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:
$('#exampleBtn').click(function() {
function();
});
In a translation unit within the same namespace, usually at the top:
// foo.h
struct foo
{
static const std::string s;
};
// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives
// bar.h
namespace baz
{
struct bar
{
static const float f;
};
}
// bar.cpp
namespace baz
{
const float bar::f = 3.1415926535;
}
if there is one error in the the submit function,the submit function will be execute. in other sentences prevent default(or return false) does not work when one error exist in submit function.
You can trick MySQL into thinking you are actually specifying a primary key column. This allows you to "override" safe mode.
Assuming you have a table with an auto-incrementing numeric primary key, you could do the following:
DELETE FROM tbl WHERE id <> 0
MyModel._meta.get_all_field_names()
was deprecated several versions back and removed in Django 1.10.
Here's the backwards-compatible suggestion from the docs:
from itertools import chain
list(set(chain.from_iterable(
(field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
for field in MyModel._meta.get_fields()
# For complete backwards compatibility, you may want to exclude
# GenericForeignKey from the results.
if not (field.many_to_one and field.related_model is None)
)))
On Microsoft Windows, gvim wouldn't allow you to select non-monospaced fonts. Unfortunately Latha is a non-monospaced font.
There is a hack way to make it happen: Using FontForge (you can download Windows binary from http://www.geocities.jp/meir000/fontforge/) to edit the Latha.ttf and mark it as a monospaced font. Doing like this:
Good luck!
I wanted to add my solution since the accepted one didn't quite work for me.
I needed to add a directive but also keep mine on the element.
In this example I am adding a simple ng-style directive to the element. To prevent infinite compile loops and allowing me to keep my directive I added a check to see if what I added was present before recompiling the element.
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
For Angular 6+ things have changed a little.
Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"outputPath": "dist/my-app-name",
Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.
You can overwrite the output path using command line arguments (e.g. for CI jobs):
ng build -op dist/example
ng build --output-path=dist/example
S.a. https://github.com/angular/angular-cli/wiki/build
Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.
To make it work in a sub directory, you'll have to set the base href.
In angular.json:
{
"projects": {
"my-app-name": {
"architect": {
"options": {
"baseHref": "/my-folder/",
Cli:
ng build --base-href=/my-folder/
If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.
Here's an example how we do it in our docker container:
entrypoint.sh
if [ -n "${BASE_PATH}" ]
then
files=( $(find . -name "index.html") )
cp -n "${files[0]}" "${files[0]}.org"
cp "${files[0]}.org" "${files[0]}"
sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi
Starting with @Ravi's answer, I also applied some validation rules for the NPA (Area) Code.
In particular:
There are a couple other restrictions, including reserved blocks (N9X, 37X, 96X) and 555, but I left those out, particularly because the reserved blocks may see future use, and 555 is useful for testing.
This is what I came up with:
^((\+\d{1,2}|1)[\s.-]?)?\(?[2-9](?!11)\d{2}\)?[\s.-]?\d{3}[\s.-]?\d{4}$
Alternately, if you also want to match blank values (if the field isn't required), you can use:
(^((\+\d{1,2}|1)[\s.-]?)?\(?[2-9](?!11)\d{2}\)?[\s.-]?\d{3}[\s.-]?\d{4}$|^$)
My test cases for valid numbers (many from @Francis' answer) are:
18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1.800.555.1234
+1.800.555.1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
My invalid test cases include:
(003) 555-1212 // Area code starts with 0
(103) 555-1212 // Area code starts with 1
(911) 555-1212 // Area code ends with 11
180055512345 // Too many digits
1 800 5555 1234 // Prefix code too long
+1 800 555x1234 // Invalid delimiter
+867 800 555 1234 // Country code too long
1-800-555-1234p // Invalid character
1 (800) 555-1234 // Too many spaces
800x555x1234 // Invalid delimiter
86 800 555 1212 // Non-NA country code doesn't have +
My regular expression does not include grouping to extract the digit groups, but it can be modified to include those.
As other answer mentioned depcheck
is good for check unused dependecies in your porject. Use npm outdated
command to check the outdated library.
lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission
Visit this file_get_contents vs cUrl
Basically file_get_contents for for you
$data = file_get_contents($file_url);
sc delete sericeName
Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.
An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:
public static class FileInfoExtension
{
//second parameter is need to avoid collision with native MoveTo
public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.MoveTo(destination);
}
}
Then use brand new MoveTo extension:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);
There is nothing in include/require that prohibits you from using absolute an path. so your example
include('/includes/header.php');
should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)
This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.
This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.
as for the '.'
syntax:
/home/username/public_html <- absolute path public_html <- relative path ./public_html <- same as the path above ../username/public_html <- another relative path
However, I usually use a slightly different option:
require_once(__DIR__ . '/Factories/ViewFactory.php');
With this edition, you specify an absolute path, relative to the file that contains the require_once()
statement.
I will explain it verbally first and then with an example:
A pointer object can be declared as a const pointer or a pointer to a const object (or both):
A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.
A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.
A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.
Example:
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = 0; // Error! Cannot modify the pointer
}
Happy to help! Good Luck!
bs := string(body)
should be enough to give you a string.
From there, you can use it as a regular string.
A bit as in this thread:
var client http.Client
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
log.Info(bodyString)
}
See also GoByExample.
As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)
?" (reverse problem, but the same conclusion apply) where zzzz mentioned:
Some conversions are the same as a cast, like
uint(myIntvar)
, which just reinterprets the bits in place.
Sonia adds:
Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. Thebytes.Buffer
type is often useful.
earl's answer gives you the solution, but I thought I'd add what the problem is that's causing your IllegalStateException
. You're calling group(1)
without having first called a matching operation (such as find()
). This isn't needed if you're just using $1
since the replaceAll()
is the matching operation.
There are two operators in Python for the "not equal" condition -
a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.
b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.
UPDATE Table SET Column = REPLACE(Column, char(9), '')
Below procedure worked for me to resolve all the escaping issues and have the procedure more a generic utility.
CREATE PROCEDURE `export_table`(
IN tab_name varchar(50),
IN select_columns varchar(1000),
IN filename varchar(100),
IN where_clause varchar(1000),
IN header_row varchar(2000))
BEGIN
INSERT INTO impl_log_activities(TABLE_NAME, LOG_MESSAGE,CREATED_TS) values(tab_name, where_clause,sysdate());
COMMIT;
SELECT CONCAT( "SELECT ", header_row,
" UNION ALL ",
"SELECT ", select_columns,
" INTO OUTFILE ", "'",filename,"'"
" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '""' ",
" LINES TERMINATED BY '\n'"
" FROM ", tab_name, " ",
(case when where_clause is null then "" else where_clause end)
) INTO @SQL_QUERY;
INSERT INTO impl_log_activities(TABLE_NAME, LOG_MESSAGE,CREATED_TS) values(tab_name, @SQL_QUERY, sysdate());
COMMIT;
PREPARE stmt FROM @SQL_QUERY;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.
check out android:textScaleX
Depending on how much spacing you need, this might help. That's the only thing remotely related to letter-spacing in the TextView.
Edit: please see @JerabekJakub's response below for an updated, better method to do this starting with api 21 (Lollipop)
If you have a virtual device with root access, this should do the job:
$ > adb shell
generic_x86:/ $
generic_x86:/ $ exit
$ > adb root
restarting adbd as root
$ > adb shell
generic_x86:/ #
If you don't, you might be interested in this answer to a different question, which explains how to create an virtual device with root access, with Google APIs (aka Google Play services), but without the Google Play app.
If you really need the Google Play app, you might be interested in other answers which instruct how to root an Android virtual device.
32-bit builds of PHP:
64-bit builds of PHP:
Numbers are inclusive.
Note: some 64-bit builds once used 32-bit integers, particularly older Windows builds of PHP
Values outside of these ranges are represented by floating point values, as are non-integer values within these ranges. The interpreter will automatically determine when this switch to floating point needs to happen based on whether the result value of a calculation can't be represented as an integer.
PHP has no support for "unsigned" integers as such, limiting the maximum value of all integers to the range of a "signed" integer.
I just input some value that I knew was invalid and here is the output:
'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.
So values you can pass to event are
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
I don't know if it's possible to run it just like that.
I usually first copy it with scp and then log in to run it.
scp foo.sh user@host:~
ssh user@host
./foo.sh
While creating the matrix X
and Y
vector use values
.
X=dataset.iloc[:,4].values
Y=dataset.iloc[:,0:4].values
It will definitely solve your problem.
This is the answer that worked for me. Was in the comments above, but deserves its rightful place as answer for ubuntu 12.04 ruby 1.8.7
sudo apt-get install ruby-dev
# if above doesnt work make sure you have build essential
sudo apt-get install build-essential
Clear the cache directory where appropriate for your system
Linux and Unix
~/.cache/pip # and it respects the XDG_CACHE_HOME directory.
OS X
~/Library/Caches/pip
Windows
%LocalAppData%\pip\Cache
With pip 20.1
or later, you can find the full path for your operating system easily by typing this in the command line:
pip cache dir
Example output on my Ubuntu installation:
? pip3 cache dir
/home/tawanda/.cache/pip
You don't need to escape the '
character in a String (wrapped in "
), and you don't have to escape a "
character in a char (wrapped in '
).
Python lists (which are not just arrays because their size can be changed on the fly) are normal Python objects and can be passed in to functions as any variable. The * syntax is used for unpacking lists, which is probably not something you want to do now.
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
I tried the approach mentioned by Onkaar Singh,
But the problem is it didn't work for the Apis which requires authorisation.
This was my curl request:
curl -v -H "Accept: application/json" -H "Content-type:
application/json" -X POST -d '
{"customer_id":"812122", "event":"add_to_cart", "email": "[email protected]", }'
-u 9f4d7f5445e7: https://api.myapp.com/api/event
After importing the body got imported correctly, the headers and the Url also got imported. Only the api key 9f4d7f5445e7 which is
-u 9f4d7f5445e7: https://api.myapp.com/api/v1/event
in the curl request did not import.
The way I solved it is, -u is basically used for Authorization. So while using it in Postman, you have to take the API key (which is 9f4d7f5445e7
in this case) and do Base64 Encode. Once encoded it will return the value OWY0ZDdmNTQ0NWU3
. Then add a new header, the key name would be Authorization
and key value would be Basic OWY0ZDdmNTQ0NWU3
. After making that changes, the request worked for me.
There are online Base64 Encoders available, the one I used is http://www.url-encode-decode.com/base64-encode-decode/
Hope it helps!!!
I want to add on to the accepted answer which works partially, but is missing the time variable, that makes it perfect.
Simplest left to right swipe detector with a time variable:
In your activity class add following attributes:
private float x1,x2;
private long startClickTime;
static final int MIN_DISTANCE = 150;
static final int MAX_SWIPE_TIME = 200;
and override onTouchEvent () method:
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
startClickTime = Calendar.getInstance().getTimeInMillis();
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE && clickDuration < MAX_SWIPE_TIME)
{
Toast.makeText(this, "left2right swipe", Toast.LENGTH_SHORT).show ();
}
else
{
// consider as something else - a screen tap for example
}
break;
}
return super.onTouchEvent(event);
}
It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)
Am i understanding your question only? You need .bat file to compile and execute java class files?
if its a .bat file. you can just double click.
and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main
If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.
With Homebrew and jenv:
Assumption: Mac machine and you already have installed homebrew.
Install cask:
$ brew tap caskroom/cask
$ brew tap caskroom/versions
To install latest java:
$ brew cask install java
To install java 8:
$ brew cask install java8
To install java 9:
$ brew cask install java9
If you want to install/manage multiple version then you can use 'jenv':
Install and configure jenv:
$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
Add the installed java to jenv:
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home
To see all the installed java:
$ jenv versions
Above command will give the list of installed java:
* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea
Configure the java version which you want to use:
$ jenv global oracle64-1.6.0.39
I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:
The screencast shows several common usages of the Unity IoC, such as:
d = <dict>
values = d.values()
The accepted answer is wrong !
Since JavaScript is asynchronous, the values of the variable end of the accepted answer would be wrong.
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// JavaScript is not waiting until the for is finished !!
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
The execution of the for may be very fast so you can not see that the result is wrong. You can test it with a code doing some request :
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
$.ajax({
url: 'www.oneOfYourWebsites.com',
success: function(){
console.log("success");
}
});
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
So the alert will prompt very quickly but in the console you'll see that the ajax requests are continuing.
Here is how you should do it : https://developer.mozilla.org/en-US/docs/Web/API/Performance.now
in jQuery:
$("#strings").val(["Test", "Prof", "Off"]);
or in pure JavaScript:
var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
jQuery does significant abstraction here.
If you get a message from git complaining about the value 'simple' in the configuration, check your git version.
After upgrading Xcode (on a Mac running Mountain Lion), which also upgraded git from 1.7.4.4 to 1.8.3.4, shells started before the upgrade were still running git 1.7.4.4 and complained about the value 'simple' for push.default in the global config.
The solution was to close the shells running the old version of git and use the new version.
Use std::this_thread::sleep_for
:
#include <chrono>
#include <thread>
std::chrono::milliseconds timespan(111605); // or whatever
std::this_thread::sleep_for(timespan);
There is also the complementary std::this_thread::sleep_until
.
Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep
function for Windows or Unix:
#ifdef _WIN32
#include <windows.h>
void sleep(unsigned milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void sleep(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
#endif
But a much simpler pre-C++11 method is to use boost::this_thread::sleep
.
It's a tree, and there may be nested elements. Try:
def innerText(self, sep=''):
t = ""
for curNode in self.childNodes:
if (curNode.nodeType == Node.TEXT_NODE):
t += sep + curNode.nodeValue
elif (curNode.nodeType == Node.ELEMENT_NODE):
t += sep + curNode.innerText(sep=sep)
return t
I've started using LinqPad. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!
The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
A variation on the 'digit' solutions offered here:
char separator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));
Taking into account the locale separator.
Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();
The method for local Is the error
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...
For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:
When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.
More info:
This is my favorite approach...
_dataGrid.DataBindingComplete += (o, _) =>
{
var dataGridView = o as DataGridView;
if (dataGridView != null)
{
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.Columns[dataGridView.ColumnCount-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
};
They both work the same way, but $_POST
should be used as it is cleaner. You can add isset()
to it to check it exists.
There is a hackish way to do this (add callbacks or resolve some deferred/promise implementation instead of alert()
calls):
var result = null;
$('<input type="file" />')
.on('change', function () {
result = this.files[0];
alert('selected!');
})
.click();
setTimeout(function () {
$(document).one('mousemove', function () {
if (!result) {
alert('cancelled');
}
});
}, 1000);
How it works: while file selection dialog is open, document does not receive mouse pointer events. There is 1000ms delay to allow the dialog to actually appear and block browser window. Checked in Chrome and Firefox (Windows only).
But this is not a reliable way to detect cancelled dialog, of course. Though, might improve some UI behavior for you.
var day = value.Date; // a DateTime that will just be whole days
var time = value.TimeOfDay; // a TimeSpan that is the duration into the day
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
Use import scala.collection.mutable.MutableList or similar if you really need mutation.
import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)
I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.
So inside an *ngFor:
<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>
And inside the component:
section = 'allwork';
shouldShrink(cat1, cat2) {
return this.section === cat1 || this.section === cat2 ? false : true;
}
Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
If you are using just code like this below, you must put just a grave accent at the end of line `
.
docker run -d --name rabbitmq ` -p 5672:5672 ` -p 15672:15672 ` --restart=always ` --hostname rabbitmq-master ` -v c:\docker\rabbitmq\data:/var/lib/rabbitmq ` rabbitmq:latest
GCC compilers always try to compile your program if this is at all possible. However, in some
cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers
such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example,
the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter
-pedantic-errors
option converts such diagnostic warnings into errors that will cause compilation
to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming
compiler will generate warnings or errors.
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS
<style type="text/css">
#nav-ask{ display:none; }
</style>
or if you already have a "hideMe" CSS Class:
<script type="text/javascript">
if(document.getElementById && document.createTextNode)
{
if(document.getElementById('nav-ask'))
{
document.getElementById('nav-ask').className='hideMe';
}
}
</script>
DAYS360
does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-
) or MINUS()
. I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.
Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]
I answered something like this in another question already, but will change it just a little for this one.
Unfortunately, there is no getImageResource()
or getDrawableId()
. But, I created a simple workaround by using the ImageView tags.
In onCreate():
imageView0 = (ImageView) findViewById(R.id.imageView0);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView0.setTag(R.drawable.apple);
imageView1.setTag(R.drawable.banana);
imageView2.setTag(R.drawable.cereal);
Then, if you like, you can create a simple function to get the drawable id:
private int getDrawableId(ImageView iv) {
return (Integer) iv.getTag();
}
Too easy.
An Activity is a user interface component that are mainly used to construct a single screen of application, and represents the main focus of attention on a screen.
In contrast, Fragments, introduced in Honeycomb(3.0) as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities.
Fragments must be hosted by an activity and an activity can host one or more fragments at a time. And a fragment’s lifecycle is directly affected by its host activity’s lifecycle.
While it’s possible to develop a UI only using Activities, this is generally a bad idea since their code cannot later be reused within other Activities, and cannot support multiple screens. In contrast, these are advantages that come with the use of Fragments: optimized experiences based on device size and well-structured, reusable code.
I think you understand everything Interfaces do, but you're not yet imagining the situations in which an Interface is useful.
If you're instantiating, using and releasing an object all within a narrow scope (for example, within one method call), an Interface doesn't really add anything. Like you noted, the concrete class is known.
Where Interfaces are useful is when an object needs to be created one place and returned to a caller that may not care about the implementation details. Let's change your IBox example to an Shape. Now we can have implementations of Shape such as Rectangle, Circle, Triangle, etc., The implementations of the getArea() and getSize() methods will be completely different for each concrete class.
Now you can use a factory with a variety of createShape(params) methods which will return an appropriate Shape depending on the params passed in. Obviously, the factory will know about what type of Shape is being created, but the caller won't have to care about whether it's a circle, or a square, or so on.
Now, imagine you have a variety of operations you have to perform on your shapes. Maybe you need to sort them by area, set them all to a new size, and then display them in a UI. The Shapes are all created by the factory and then can be passed to the Sorter, Sizer and Display classes very easily. If you need to add a hexagon class some time in the future, you don't have to change anything but the factory. Without the Interface, adding another shape becomes a very messy process.
I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.
Some of the system headers provide a forward declaration of std::stringstream
without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream>
header:
#include <sstream>
You can just use an import statement:
from file import *
So, for example, if you had a file named my_script.py
you'd load it like so:
from my_script import *
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
When you say pair[0]
, that gives you ("a", 1)
. The thing in parentheses is a tuple, which, like a list, is a type of collection. So you can access the first element of that thing by specifying [0]
or [1]
after its name. So all you have to do to get the first element of the first element of pair
is say pair[0][0]
. Or if you want the second element of the third element, it's pair[2][1]
.
First You will need to enable the query log by calling:
DB::enableQueryLog();
after queries using the DB facade you can write:
dd(DB::getQueryLog());
the output will like below:
array:1 [?
0 => array:3 [?
"query" => "select * from `users` left join `website_user` on `users`.`id` = `website_user`.`user_id` left join `region_user` on `users`.`id` = `region_user`.`user_id` left ?"
"bindings" => array:5 [?]
"time" => 3.79
]
]
Just another solution using underscore.js:
_.extend({}, obj1, obj2);
EventHandler.GetInvocationList().Length > 0
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
.btn
is the best way, in modern website, it's not good while using anchor element
without href
so make the anchor tag
to button
is better.
Alternatively, you could do the following:
Dictionary<FunkyAttributesEnum, string> description = new Dictionary<FunkyAttributesEnum, string>()
{
{ FunkyAttributesEnum.NameWithoutSpaces1, "Name With Spaces1" },
{ FunkyAttributesEnum.NameWithoutSpaces2, "Name With Spaces2" },
};
And get the description with the following:
string s = description[FunkyAttributesEnum.NameWithoutSpaces1];
In my opinion this is a more efficient way of doing what you want to accomplish, as no reflection is needed..
Strictly, method a
is the least resource intensive:
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
Proven less CPU intensive for the same total duration a million rows by someone with way too much time on their hands: Most efficient way in SQL Server to get a date from date+time?
I saw a similar test elsewhere with similar results too.
I prefer the DATEADD/DATEDIFF because:
Edit, Oct 2011
For SQL Server 2008+, you can CAST to date
i.e. CAST(getdate() AS date)
. Or just use date
datatype so no time
to remove.
Edit, Jan 2012
A worked example of how flexible this is: Need to calculate by rounded time or date figure in sql server
Edit, May 2012
Do not use this in WHERE clauses and the like without thinking: adding a function or CAST to a column invalidates index usage. See number 2 here Common SQL Programming Mistakes
Now, this does have an example of later SQL Server optimiser versions managing CAST to date correctly, but generally it will be a bad idea ...
Edit, Sep 2018, for datetime2
DECLARE @datetime2value datetime2 = '02180912 11:45' --this is deliberately within datetime2, year 0218
DECLARE @datetime2epoch datetime2 = '19000101'
select DATEADD(dd, DATEDIFF(dd, @datetime2epoch, @datetime2value), @datetime2epoch)
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
There is also another solution which will be to override systemFont.
Just create a category
UIFont+SystemFontOverride.h
#import <UIKit/UIKit.h>
@interface UIFont (SystemFontOverride)
@end
UIFont+SystemFontOverride.m
@implementation UIFont (SystemFontOverride)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize {
return [UIFont fontWithName:@"fontName" size:fontSize];
}
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize {
return [UIFont fontWithName:@"fontName" size:fontSize];
}
#pragma clang diagnostic pop
@end
This will replace the default implementation and most UIControls use systemFont.
The Python executable might be installed at a location other than /usr/bin, but env
is nearly always present in that location so using /usr/bin/env
is more portable.
Given what you've tried and the error messages, I'd say this was more to do with the exact cipher algorithm used rather than the TLS/SSL version. Are you using a non-Sun JRE by any chance, or a different vendor's security implementation? Try a different JRE/OS to test your server if you can. Failing that you might just be able to see what's going on with Wireshark (with a filter of 'tcp.port == 443').
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue
I've created SASS mixin definitions based on bootstrap definitions for any number of columns (personally beside 12 I use 8, 10 and 24):
// Extended bootstrap grid system
//
// Framework grid generation
//
// Based on Bootstrap 'bootstrap/_grid-framework.scss'. Generates classes in form of `.col-(size)-x-num` of width x/num.
@mixin make-extended-grid-columns($num-columns, $i: 1, $list: ".col-xs-#{$i}-#{$num-columns}, .col-sm-#{$i}-#{$num-columns}, .col-md-#{$i}-#{$num-columns}, .col-lg-#{$i}-#{$num-columns}") {
@for $i from (1 + 1) through $num-columns {
$list: "#{$list}, .col-xs-#{$i}-#{$num-columns}, .col-sm-#{$i}-#{$num-columns}, .col-md-#{$i}-#{$num-columns}, .col-lg-#{$i}-#{$num-columns}";
}
#{$list} {
position: relative;
min-height: 1px;
padding-left: ($grid-gutter-width / 2);
padding-right: ($grid-gutter-width / 2);
}
}
@mixin float-extended-grid-columns($class, $num-columns, $i: 1, $list: ".col-#{$class}-#{$i}-#{$num-columns}") {
@for $i from (1 + 1) through $num-columns {
$list: "#{$list}, .col-#{$class}-#{$i}-#{$num-columns}";
}
#{$list} {
float: left;
}
}
@mixin calc-extended-grid-column($index, $num-columns, $class, $type) {
@if ($type == width) and ($index > 0) {
.col-#{$class}-#{$index}-#{$num-columns} {
width: percentage(($index / $num-columns));
}
}
@if ($type == push) and ($index > 0) {
.col-#{$class}-push-#{$index}-#{$num-columns} {
left: percentage(($index / $num-columns));
}
}
@if ($type == pull) and ($index > 0) {
.col-#{$class}-pull-#{$index}-#{$num-columns} {
right: percentage(($index / $num-columns));
}
}
@if ($type == offset) and ($index > 0) {
.col-#{$class}-offset-#{$index}-#{$num-columns} {
margin-left: percentage(($index / $num-columns));
}
}
}
@mixin loop-extended-grid-columns($num-columns, $class, $type) {
@for $i from 1 through $num-columns - 1 {
@include calc-extended-grid-column($i, $num-columns, $class, $type);
}
}
@mixin make-extended-grid($class, $num-columns) {
@include float-extended-grid-columns($class, $num-columns);
@include loop-extended-grid-columns($num-columns, $class, width);
@include loop-extended-grid-columns($num-columns, $class, pull);
@include loop-extended-grid-columns($num-columns, $class, push);
@include loop-extended-grid-columns($num-columns, $class, offset);
}
And you can simply create classes by:
$possible-number-extended-grid-columns: 8, 10, 24;
@each $num-columns in $possible-number-extended-grid-columns {
// Columns
@include make-extended-grid-columns($num-columns);
// Extra small grid
@include make-extended-grid(xs, $num-columns);
// Small grid
@media (min-width: $screen-sm-min) {
@include make-extended-grid(sm, $num-columns);
}
// Medium grid
@media (min-width: $screen-md-min) {
@include make-extended-grid(md, $num-columns);
}
// Large grid
@media (min-width: $screen-lg-min) {
@include make-extended-grid(lg, $num-columns);
}
}
I hope someone will find it useful
My experience to the same warning message was caused by TypeError.
TypeError: invalid type comparison
So, you may want to check the data type of the Unnamed: 5
for x in df['Unnamed: 5']:
print(type(x)) # are they 'str' ?
Here is how I can replicate the warning message:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 2), columns=['num1', 'num2'])
df['num3'] = 3
df.loc[df['num3'] == '3', 'num3'] = 4 # TypeError and the Warning
df.loc[df['num3'] == 3, 'num3'] = 4 # No Error
Hope it helps.
Just to augment the other answers from a different angle.
If you want to reuse hashcode(s) from 'above' and derive new ones using your class' immutatable state, then a call to super will work. While this may/may not cascade all the way up to Object (i.e. some ancestor may not call super), it will allow you to derive hashcodes by reuse.
@Override
public int hashCode() {
int ancestorHash = super.hashCode();
// now derive new hash from ancestorHash plus immutable instance vars (id fields)
}
The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.
It worked for me, but only with https link in repository setting (Repository => Repository Settings). You need to change setting to:
URL / path: https://**********.com/username/project.git Host Type - Stash Host Root URL - your root URL to GitLab (example:https://**********.com/) Username - leave blank
or in some cases if you have ssh url like:
[email protected]:USER/REPOSITORY.git
and your email like:
[email protected]
then this settings should be work:
URL / path: https://test%[email protected]:USER/REPOSITORY.git
There could be various reason for getting the SSH error:
sign_and_send_pubkey: signing failed: agent refused operation
Some of them could be related to the issues highlighted by the other answers (see this thread answers), some of them could be hidden and thus would require a closer investigation.
In my case I've got the following error message:
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic)
The only way to find the real problem was to invoke the -v verbose option which resulted in printing a lot of debugging info:
debug1: Connecting to website.domain.com [xxx.xxx.xxx.xxx] port 22.
debug1: Connection established.
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com type 0
debug1: key_load_public: No such file or directory
debug1: identity file /home/user/.ssh/id_rsa.website.domain.com-cert type -1
Please note that the line saying key_load_public: No such file or directory
is referring the next line and not the previous line.
So what SSH really says is that it could not find the public key file named id_rsa.website.domain.com-cert
and that seemed to be the problem in my case since my public key file did not contain the -cert
suffix.
Long story short: the fix in my case was just to make sure that the public key file was named as expected. I could never suspected that without debugging the connection.
The bottom line is USE THE SSH VERBOSE MODE (-v option) to figure out what is wrong, there could be various reasons, none that could be found on this/another thread.
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );_x000D_
console.log("00string =>", "00string".replace(/^0/,'') );_x000D_
console.log("string00 =>", "string00".replace(/^0/,'') );
_x000D_
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
I also got the issue but after replacing existing one with the downloaded (from JCE) one resolved the issue. New crypto files provided unlimited strength.
I hope you have resolved your issue. If you still got issue then double check again if you install this Oracle under a domain account. I found a thread that says Oracle XE giving same error when installing under domain account. Please use a local account instead.
Source:
https://community.oracle.com/thread/2141735?start=0&tstart=0
In python 3 we can start make use of the unpack asterisk. Given two lists:
bool(len({*a} & {*b}))
Edit: incorporate alkanen's suggestion
<a [routerLink]="[{ outlets: { list:['streams'], details:['parties'] } }]">Link</a>
<div id="list">
<router-outlet name="list"></router-outlet>
</div>
<div id="details">
<router-outlet name="details"></router-outlet>
</div>
`
{
path: 'admin',
component: AdminLayoutComponent,
children:[
{
path: '',
component: AdminStreamsComponent,
outlet:'list'
},
{
path: 'stream/:id',
component: AdminStreamComponent,
outlet:'details'
}
]
}
Came across similar scenario and the CASE expression was useful to me.
UPDATE reports SET is_default =
case
when report_id = 123 then true
when report_id != 123 then false
end
WHERE account_id = 321;
Reports - is a table here, account_id is same for the report_ids mentioned above. The above query will set 1 record (the one which matches the condition) to true and all the non-matching ones to false.
Responding to @1290. Sorry, no way to format blocks in comments. The None
value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString
. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None)
produces 'None'
, a non-blank string.
However if you must treat None
and (spaces) as "blank" strings, here is a better way:
class weirdstr(str):
def __new__(cls, content):
return str.__new__(cls, content if content is not None else '')
def __nonzero__(self):
return bool(self.strip())
Examples:
>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True
>>> spaces = weirdstr(' ')
>>> print spaces, bool(spaces)
False
>>> blank = weirdstr('')
>>> print blank, bool(blank)
False
>>> none = weirdstr(None)
>>> print none, bool(none)
False
>>> if not spaces:
... print 'This is a so-called blank string'
...
This is a so-called blank string
Meets the @rouble requirements while not breaking the expected bool
behavior of strings.
To answer the first part of your question:
LPCSTR
is a pointer to a const string (LP means Long Pointer)
LPCTSTR
is a pointer to a const TCHAR
string, (TCHAR
being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR
is a pointer to a (non-const) TCHAR
string
In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
As was pointed out, a semaphore with a count of one is the same thing as a 'binary' semaphore which is the same thing as a mutex.
The main things I've seen semaphores with a count greater than one used for is producer/consumer situations in which you have a queue of a certain fixed size.
You have two semaphores then. The first semaphore is initially set to be the number of items in the queue and the second semaphore is set to 0. The producer does a P operation on the first semaphore, adds to the queue. and does a V operation on the second. The consumer does a P operation on the second semaphore, removes from the queue, and then does a V operation on the first.
In this way the producer is blocked whenever it fills the queue, and the consumer is blocked whenever the queue is empty.
In ~/.subversion/auth/svn.simple/
you should find a file with a long hexadecimal name. The password is in there in plaintext.
If there is more than one file you'll need to find that one that references the server you need the password for.
You don't need to calculate anything, and probably shouldn't:
<!DOCTYPE html>
<head>
<style type="text/css">
body {background: blue; height:100%;}
header {background: red; height: 20px; width:100%}
h1 {font-size:1.2em; margin:0; padding:0;
height: 30px; font-weight: bold; background:yellow}
.theCalcDiv {background-color:green; padding-bottom: 100%}
</style>
</head>
<body>
<header>Some nav stuff here</header>
<h1>This is the heading</h1>
<div class="theCalcDiv">This blocks needs to have a CSS calc() height of 100% - the height of the other elements.
</div>
I stuck it all together for brevity.
I think this is the best and easy way:
$lista = @()
$lista += ('{"name": "Diego" }' | ConvertFrom-Json)
$lista += ('{"name": "Monica" }' | ConvertFrom-Json)
$lista += ('{"name": "Celia" }' | ConvertFrom-Json)
$lista += ('{"name": "Quin" }' | ConvertFrom-Json)
if ("Diego" -in $lista.name) {
Write-Host "is in the list"
return $true
}
else {
Write-Host "not in the list"
return $false
}
Specify crossAxisAlignment: CrossAxisAlignment.start
in your column
You could also turn on autoextend for the whole database using this command:
ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;
Just change the filepath to point to your system.dbf file.
Credit Here
In my case i made the following mistake in my css code.
*{
font-family: 'Open Sans', sans-serif !important;
}
This will override all font family rules for the entire page. My solution was to move the code to body like so.
body{
font-family: 'Open Sans', sans-serif;
}
NB: Whenever you use the !important
flag in css, any other css rule declared of the same type on the same element will get overriden.
SharpSSH should do the job. http://www.codeproject.com/Articles/11966/sharpSsh-A-Secure-Shell-SSH-library-for-NET
Enable the "strip" extension and type the following:
hg strip #changeset# --keep
Where #changeset#
is the hash for the changeset you want to remove. This will remove the said changeset including changesets that descend from it and will leave your working directory untouched. If you wish to also revert your committed code changes remove the --keep
option.
For more information, check the Strip Extension.
If you get "unkown command 'strip'" you may need to enable it. To do so find the .hgrc
or Mercurial.ini
file and add the following to it:
[extensions]
strip =
Note that (as Juozas mentioned in his comment) having multiple heads is normal workflow in Mercurial. You should not use the strip command to battle that. Instead, you should merge your head with the incoming head, resolve any conflicts, test, and then push.
The strip
command is useful when you really want to get rid of changesets that pollute the branch. In fact, if you're in this question's situation and you want to completely remove all "draft" change sets permanently, check out the top answer, which basically suggests doing:
hg strip 'roots(outgoing())'
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
The +
operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d
is a non-zero number.
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start. In some cases above state can stop though TCP connection to port 1433 is assigned.
Overall
SELECT
COUNT(DISTINCT `site_id`) as distinct_sites
FROM `cp_visits`
WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Or per site
SELECT
`site_id` as site,
COUNT(DISTINCT `user_id`) as distinct_users_per_site
FROM `cp_visits`
WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`
Having the time
column in the result doesn't make sense - since you are aggregating the rows, showing one particular time
is irrelevant, unless it is the min
or max
you are after.
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:
Ctrl-a [ g SPACE G $ >.
This will save your whole buffer to /tmp/screen-exchange
I found it hard to decipher what is meant by "working directory of the VM". In my example, I was using the Java Service Wrapper program to execute a jar - the dump files were created in the directory where I had placed the wrapper program, e.g. c:\myapp\bin. The reason I discovered this is because the files can be quite large and they filled up the hard drive before I discovered their location.
It appears that there is a mismatch between the View files that some versions of Visual Studio auto-generates for you when you use it to create a new Model. I encountered this problem using the new VS 2013 Community Edition and walking through the W3Schools tutorial at http://www.w3schools.com/aspnet/mvc_app.asp but the comments above indicate that its not a problem with the tutorial directions or with a single version of VS.
It is true that you can make the error message go away by just removing the
@Scripts.Render("~/bundles/jqueryval")
line from the create/edit layouts that were autogenerated by Visual Studio.
But that solution does not address the root cause or leave you in a good place to do more than finish walking through the tutorial. At some point (probably fairly early) in the development of a real application, you are going to want access to the jquery validation code that the commenting-out solution removes from your app.
If you use VS to create a new model for you, it also creates a set of five View files: Create, Delete, Details, Edit, and Index. Two of these views, Create and Edit are intended to let the user add/edit data for the fields in database records that underlie the model. For those views in a real app, you will probably want to do some amount of data validation using the jquery validation library before you save the record in the db. That is why VS adds the following lines
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
to the bottom of those two views and not others. The autogenerated code is trying to make the validation library available for those views, but not the others.
The error happens because VS either doesn't add a corresponding line to the shared _Layout.cshtml file or, see one answer above, adds it but leaves it commented out. This line is
@RenderSection("scripts", required: false)
If some of your views have a scripts section (as Create and Edit do), there has to be a RenderSection command embedded in the layout. If some scripts have the section and some do not (as Delete, Details, and Index do not), the RenderSection command has to have the required: false
parameter.
So the best solution, if you want to do anything more than just finish walking through the tutorial, is to add the statement to _Layout.cshtml not remove the code from the Edit and Create views.
P.S. It is a bit of a confuser, here, that what is being required is in a 'bundle' and the require statement looks like it is trying to include a file in a bundles folder that does not exist in your project. But, for debug builds and tutorials, that's not relevant since the bundled files get included one at a time. See: http://www.asp.net/mvc/overview/performance/bundling-and-minification The code that is at issue here is mentioned briefly about two-thirds of the way down the page.
Take a look into NSColorWell class reference.
When using jQuery you do not need to call a stop function separate.
You can just return false
in the event handler
This will stop the event and cancel bubbling..
Also see event.preventDefault() vs. return false
From the jQuery docs:
These handlers, therefore, may prevent the delegated handler from triggering by calling
event.stopPropagation()
or returningfalse
.
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.
public class Main {
public interface Visitor{
int doJob(int a, int b);
}
public static void main(String[] args) {
Visitor adder = new Visitor(){
public int doJob(int a, int b) {
return a + b;
}
};
Visitor multiplier = new Visitor(){
public int doJob(int a, int b) {
return a*b;
}
};
System.out.println(adder.doJob(10, 20));
System.out.println(multiplier.doJob(10, 20));
}
}
Is this what you are after?
select * from tempdb..sysobjects
--for sql-server 2000 and later versions
select * from tempdb.sys.objects
--for sql-server 2005 and later versions
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
Eclipse: failed to create the java virtual machine – message box
Replace -vmargs by your current real path of javaw.exe with
-vm "c:\Program Files\Java\jdk1.7.0_07\bin\javaw.exe"
or in case you've installed jre only:
-vm "C:\Program Files\Java\jre7\bin\javaw.exe"
Tilde expansion is a shell thing. Write the proper pathname (probably /home/
yourusername/Desktop/etcetcetc
) or use
process.env.HOME + '/Desktop/blahblahblah'
New answer to old question, sorry. I thought I'd add my $.02
The OP asked if the headers were encrypted.
They are: in transit.
They are NOT: when not in transit.
So, your browser's URL (and title, in some cases) can display the querystring (which usually contain the most sensitive details) and some details in the header; the browser knows some header information (content type, unicode, etc); and browser history, password management, favorites/bookmarks, and cached pages will all contain the querystring. Server logs on the remote end can also contain querystring as well as some content details.
Also, the URL isn't always secure: the domain, protocol, and port are visible - otherwise routers don't know where to send your requests.
Also, if you've got an HTTP proxy, the proxy server knows the address, usually they don't know the full querystring.
So if the data is moving, it's generally protected. If it's not in transit, it's not encrypted.
Not to nit pick, but data at the end is also decrypted, and can be parsed, read, saved, forwarded, or discarded at will. And, malware at either end can take snapshots of data entering (or exiting) the SSL protocol - such as (bad) Javascript inside a page inside HTTPS which can surreptitiously make http (or https) calls to logging websites (since access to local harddrive is often restricted and not useful).
Also, cookies are not encrypted under the HTTPS protocol, either. Developers wanting to store sensitive data in cookies (or anywhere else for that matter) need to use their own encryption mechanism.
As to cache, most modern browsers won't cache HTTPS pages, but that fact is not defined by the HTTPS protocol, it is entirely dependent on the developer of a browser to be sure not to cache pages received through HTTPS.
So if you're worried about packet sniffing, you're probably okay. But if you're worried about malware or someone poking through your history, bookmarks, cookies, or cache, you are not out of the water yet.
Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.
import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Capturing",frame)
# 6.for playing
key = cv2.waitKey(1)
if key == ord('q'):
break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows
You can see my github code here
All these answers and noone has pointed to the most popular NPM package .. cron
I just have a idea. Use the symbolic link to solve the error and you can still use your prefix for globally installed packages.
ln -s [your prefix path] [path in the '~/.nvm']
then you will have a symbolic folder in the ~/.nvm
folder, but in fact, your global packages are still installed in [your prefix path]. Then the error will not show again and you can use nvm use **
normally.
ps: it's worked for me on mac
.
pps: do not forget to set $PATH
to your npm bin
folder to use the globally installed packages.
Since Java 1.6, a java.exe is installed into %windir%\system32 that supports a "-version" command line option. You can use this to select a specific version to run, e.g.:
java -version:1.7 -jar [path to jar file]
will run a jar application in java 1.7, if it is installed.
See Oracle's documentation here: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html
You can use E6 destructuring:
Object destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled({arg1: value1, arg2: value2});
})
promise.then(({arg1, arg2}) => {
// ....
});
Array destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled([value1, value2]);
})
promise.then(([arg1, arg2]) => {
// ....
});
I'm using next approach:
ProductID OrderID,...
ProductID Title Name LanguageID
LanguageID Name Culture,....
You are looking for the CASE statement
http://msdn.microsoft.com/en-us/library/ms181765.aspx
Example copied from MSDN:
USE AdventureWorks;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
To solve the problem of mutiple inheritance in Java → interface is used
J2EE (core JAVA) Notes By Mr. K.V.R Page 51
Day - 27
- Interfaces are basically used to develop user defined data types.
- With respect to interfaces we can achieve the concept of multiple inheritances.
- With interfaces we can achieve the concept of polymorphism, dynamic binding and hence we can improve the performance of a JAVA program in turns of memory space and execution time.
An interface is a construct which contains the collection of purely undefined methods or an interface is a collection of purely abstract methods.
[...]
Day - 28:
Syntax-1 for reusing the features of interface(s) to class:
[abstract] class <clsname> implements <intf 1>,<intf 2>.........<intf n> { variable declaration; method definition or declaration; };
In the above syntax clsname represents name of the class which is inheriting the features from ‘n’ number of interfaces. ‘Implements’ is a keyword which is used to inherit the features of interface(s) to a derived class.
[...]
Syntax-2 inheriting ‘n’ number of interfaces to another interface:
interface <intf 0 name> extends <intf 1>,<intf 2>.........<intf n> { variable declaration cum initialization; method declaration; };
[...]
Syntax-3:
[abstract] class <derived class name> extends <base class name> implements <intf 1>,<intf 2>.........<intf n> { variable declaration; method definition or declaration; };
Also you can use ui-sref-active directive:
<ul>
<li ui-sref-active="active" class="item">
<a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
</li>
<!-- ... -->
</ul>
Or filters:
"stateName" | isState
& "stateName" | includedByState
Use class_=
If you want to find element(s) without stating the HTML tag.
For single element:
soup.find(class_='my-class-name')
For multiple elements:
soup.find_all(class_='my-class-name')
It looks like you added a dependency on a Paypal library but did not include that library in your project:
Caused by: java.lang.ClassNotFoundException: com.paypal.exception.SSLConfigurationException
I'm not sure which jar, but it is most likely paypal-core.jar
. Try adding it under WEB-INF/lib
.
Unfortunately you can't declare database names with a variable in that format.
For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:
DECLARE @Sql varchar(max) ='CREATE DATABASE ' + @DBNAME
Then call
EXECUTE(@Sql) or sp_executesql(@Sql)
to execute the sql string.
I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.
Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.
You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.
http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:
Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.
This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.
He suggests the following fix.
// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
String prot = getRequestingProtocol().toLowerCase();
String host = System.getProperty(prot + ".proxyHost", "");
String port = System.getProperty(prot + ".proxyPort", "80");
String user = System.getProperty(prot + ".proxyUser", "");
String password = System.getProperty(prot + ".proxyPassword", "");
if (getRequestingHost().equalsIgnoreCase(host)) {
if (Integer.parseInt(port) == getRequestingPort()) {
// Seems to be OK.
return new PasswordAuthentication(user, password.toCharArray());
}
}
}
return null;
}
});
I haven't tried it yet, but it looks good to me.
I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).
Or, just as easy:
string assyGuid = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>().Value.ToUpper();
It works for me...
Similar to David Schmitt's answer, plus Josh's suggestion, but doesn't leave a shell process running:
(cd /c && exec /a/helloworld)
This way is more similar to how you usually run commands on the shell. To see the practical difference, you have to run ps ef
from another shell with each solution.
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
const p = document.querySelector('p')_x000D_
const result = document.querySelector('div')_x000D_
const observer = new MutationObserver((mutationRecords) => {_x000D_
result.textContent = mutationRecords[0].target.data_x000D_
// result.textContent = p.textContent_x000D_
})_x000D_
observer.observe(p, {_x000D_
characterData: true,_x000D_
subtree: true,_x000D_
})
_x000D_
<p contenteditable>abc</p>_x000D_
<div />
_x000D_
What about position: relative
for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE
would ever confuse anyone who knew what they were doing.
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
Unfortunately neither display:inline-block
nor width:0px
works in Internet Explorer up to version 8. I have not tried Internet Explorer 9. Much as I would like to ignore Internet Explorer, I can't.
The only option that works on Firefox and Internet Explorer 8 is float:left
. The only slight drawback is that you have to remember to use clear:both
on the element that follows the form. Of course, it will be very obvious if you forget ;-)
One other thing. You may need to specify the -L option as well - eg
-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz
or you may end up with an error like
ld: cannot find -lbaz
There's also an option to Auto Sync built-in in Aptana.
From the manual:
Possible values for the parameter timeout: … x set timeout to x seconds
and
readlines(sizehint=None, eol='\n') Read a list of lines, until timeout. sizehint is ignored and only present for API compatibility with built-in File objects.
Note that this function only returns on a timeout.
So your readlines
will return at most every 2 seconds. Use read()
as Tim suggested.
I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.
The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?
Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
It is a little complicated, but you can draw all the objects by the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="b")
# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
# draw a point
ax.scatter([0], [0], [0], color="g", s=100)
# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
In my opinion it's a lot easier just to use the UglifyJS tool directly:
npm install --save-dev uglify-js
./dst/bundle.js
file.Add a build
command to your package.json
:
"scripts": {
"build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
}
npm run build
command.No need to install uglify-js globally, just install it locally for the project.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str = (prestationEco)o; //As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
Use the following code in your CSS
html { _x000D_
background: url(images/bg.jpg) no-repeat center center fixed; _x000D_
-webkit-background-size: cover;_x000D_
-moz-background-size: cover;_x000D_
-o-background-size: cover;_x000D_
background-size: cover;_x000D_
}
_x000D_
I would use @HostListener decorator within your component:
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
There are also other options like:
host property within @Component
decorator
Angular recommends using @HostListener
decorator over host property https://angular.io/guide/styleguide#style-06-03
@Component({
...
host: {
'(document:keypress)': 'handleKeyboardEvent($event)'
}
})
export class AppComponent {
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
}
}
renderer.listen
import { Component, Renderer2 } from '@angular/core';
@Component({
...
})
export class AppComponent {
globalListenFunc: Function;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
console.log(e);
});
}
ngOnDestroy() {
// remove listener
this.globalListenFunc();
}
}
Observable.fromEvent
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
@Component({
...
})
export class AppComponent {
subscription: Subscription;
ngOnInit() {
this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
console.log(e);
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Here's my version after reading the documentation provided by Apple and the previous posts. One thing I noticed is that the textView was not handled when covered by the keyboard. Unfortunately, Apple's documentation won't work because, for whatever reason, the keyboard is called AFTER the textViewDidBeginEditing is called. I handled this by calling a central method that checks if the keyboard is displayed AND if a textView or textField is being edited. This way, the process is only fired when BOTH conditions exists.
Another point with textViews is that their height may be such that the keyboard clips the bottom of the textView and would not adjust if the Top-Left point of the was in view. So, the code I wrote actually takes the screen-referenced Bottom-Left point of any textView or textField and sees if it falls in the screen-referenced coordinates of the presented keyboard implying that the keyboard covers some portion of it.
let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY))) {
// scroll textView/textField into view
}
If you're using a navigation controller, the subclass also sets the scroll view automatic adjustment for insets to false.
self.automaticallyAdjustsScrollViewInsets = false
It walks through each textView and textField to set delegates for handling
for view in self.view.subviews {
if view is UITextView {
let tv = view as! UITextView
tv.delegate = self
} else if view is UITextField {
let tf = view as! UITextField
tf.delegate = self
}
}
Simply set your base class to the subclass created here for results.
import UIKit
class ScrollingFormViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {
var activeFieldRect: CGRect?
var keyboardRect: CGRect?
var scrollView: UIScrollView!
override func viewDidLoad() {
self.automaticallyAdjustsScrollViewInsets = false
super.viewDidLoad()
// Do any additional setup after loading the view.
self.registerForKeyboardNotifications()
for view in self.view.subviews {
if view is UITextView {
let tv = view as! UITextView
tv.delegate = self
} else if view is UITextField {
let tf = view as! UITextField
tf.delegate = self
}
}
scrollView = UIScrollView(frame: self.view.frame)
scrollView.scrollEnabled = false
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.addSubview(self.view)
self.view = scrollView
}
override func viewDidLayoutSubviews() {
scrollView.sizeToFit()
scrollView.contentSize = scrollView.frame.size
super.viewDidLayoutSubviews()
}
deinit {
self.deregisterFromKeyboardNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func registerForKeyboardNotifications()
{
//Adding notifies on keyboard appearing
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWasShown), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ScrollingFormViewController.keyboardWillBeHidden), name: UIKeyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications()
{
//Removing notifies on keyboard appearing
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification)
{
let info : NSDictionary = notification.userInfo!
keyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
adjustForKeyboard()
}
func keyboardWillBeHidden(notification: NSNotification)
{
keyboardRect = nil
adjustForKeyboard()
}
func adjustForKeyboard() {
if keyboardRect != nil && activeFieldRect != nil {
let aRect : CGRect = scrollView.convertRect(activeFieldRect!, toView: nil)
if (CGRectContainsPoint(keyboardRect!, CGPointMake(aRect.origin.x, aRect.maxY)))
{
scrollView.scrollEnabled = true
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardRect!.size.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
scrollView.scrollRectToVisible(activeFieldRect!, animated: true)
}
} else {
let contentInsets : UIEdgeInsets = UIEdgeInsetsZero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
scrollView.scrollEnabled = false
}
}
func textViewDidBeginEditing(textView: UITextView) {
activeFieldRect = textView.frame
adjustForKeyboard()
}
func textViewDidEndEditing(textView: UITextView) {
activeFieldRect = nil
adjustForKeyboard()
}
func textFieldDidBeginEditing(textField: UITextField)
{
activeFieldRect = textField.frame
adjustForKeyboard()
}
func textFieldDidEndEditing(textField: UITextField)
{
activeFieldRect = nil
adjustForKeyboard()
}
}
Try the following shell command (replace DB_NAME
with your database name):
mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head
For Drupal/drush solution, check the following example script which will display the biggest tables in use:
#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20
docker exec
will definitely be a solution. An easy way to work with the question you asked is by mounting the directory inside Docker to the local system's directory.
So that you can view the changes in local path instantly.
docker run -v /Users/<path>:/<container path>
If you want to take a copy of a live database, do the Backup/Restore method.
[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.
std::getline( stream, where to?, delimiter ie
std::string in;
std::getline(std::cin, in, ' '); //will split on space
or you can read in a line, then tokenize it based on whichever delimiter you wish.
Your implementation (the one in the question) is faster than e.g. wrapping with toList()
and using a comparator-based method. Auto-boxing and running through comparator methods or wrapped Collections objects is far slower than just reversing.
Of course you could write your own sort. That might not be the answer you're looking for, but note that if your comment about "if the array is already sorted quite well" happens frequently, you might do well to choose a sorting algorithm that handles that case well (e.g. insertion) rather than use Arrays.sort()
(which is mergesort, or insertion if the number of elements is small).