I decided to take a look at this for fun, and here are the timings that I get:
Swift 4.0.2 : 0.83s (0.74s with `-Ounchecked`)
C++ (Apple LLVM 8.0.0): 0.74s
// Swift 4.0 code
import Foundation
func doTest() -> Void {
let arraySize = 10000000
var randomNumbers = [UInt32]()
for _ in 0..<arraySize {
randomNumbers.append(arc4random_uniform(UInt32(arraySize)))
}
let start = Date()
randomNumbers.sort()
let end = Date()
print(randomNumbers[0])
print("Elapsed time: \(end.timeIntervalSince(start))")
}
doTest()
Results:
Swift 1.1
xcrun swiftc --version
Swift version 1.1 (swift-600.0.54.20)
Target: x86_64-apple-darwin14.0.0
xcrun swiftc -O SwiftSort.swift
./SwiftSort
Elapsed time: 1.02204304933548
Swift 1.2
xcrun swiftc --version
Apple Swift version 1.2 (swiftlang-602.0.49.6 clang-602.0.49)
Target: x86_64-apple-darwin14.3.0
xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort
Elapsed time: 0.738763988018036
Swift 2.0
xcrun swiftc --version
Apple Swift version 2.0 (swiftlang-700.0.59 clang-700.0.72)
Target: x86_64-apple-darwin15.0.0
xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort
Elapsed time: 0.767306983470917
It seems to be the same performance if I compile with -Ounchecked
.
Swift 3.0
xcrun swiftc --version
Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9
xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort
Elapsed time: 0.939633965492249
xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
./SwiftSort
Elapsed time: 0.866258025169373
There seems to have been a performance regression from Swift 2.0 to Swift 3.0, and I'm also seeing a difference between -O
and -Ounchecked
for the first time.
Swift 4.0
xcrun swiftc --version
Apple Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38)
Target: x86_64-apple-macosx10.9
xcrun -sdk macosx swiftc -O SwiftSort.swift
./SwiftSort
Elapsed time: 0.834299981594086
xcrun -sdk macosx swiftc -Ounchecked SwiftSort.swift
./SwiftSort
Elapsed time: 0.742045998573303
Swift 4 improves the performance again, while maintaining a gap between -O
and -Ounchecked
. -O -whole-module-optimization
did not appear to make a difference.
#include <chrono>
#include <iostream>
#include <vector>
#include <cstdint>
#include <stdlib.h>
using namespace std;
using namespace std::chrono;
int main(int argc, const char * argv[]) {
const auto arraySize = 10000000;
vector<uint32_t> randomNumbers;
for (int i = 0; i < arraySize; ++i) {
randomNumbers.emplace_back(arc4random_uniform(arraySize));
}
const auto start = high_resolution_clock::now();
sort(begin(randomNumbers), end(randomNumbers));
const auto end = high_resolution_clock::now();
cout << randomNumbers[0] << "\n";
cout << "Elapsed time: " << duration_cast<duration<double>>(end - start).count() << "\n";
return 0;
}
Results:
Apple Clang 6.0
clang++ --version
Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort
Elapsed time: 0.688969
Apple Clang 6.1.0
clang++ --version
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort
Elapsed time: 0.670652
Apple Clang 7.0.0
clang++ --version
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort
Elapsed time: 0.690152
Apple Clang 8.0.0
clang++ --version
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort
Elapsed time: 0.68253
Apple Clang 9.0.0
clang++ --version
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
clang++ -O3 -std=c++11 CppSort.cpp -o CppSort
./CppSort
Elapsed time: 0.736784
As of the time of this writing, Swift's sort is fast, but not yet as fast as C++'s sort when compiled with -O
, with the above compilers & libraries. With -Ounchecked
, it appears to be as fast as C++ in Swift 4.0.2 and Apple LLVM 9.0.0.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)This tool gave me following results which helps me achieve the task as following code.
<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
function play(){
document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
}
</script>
Simplistic way is,if you are using listview in a xml,use this attributes on your listview,
android:choiceMode="singleChoice"
android:listSelector="#your color code"
if not using xml,by programatically
listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);
$(document).ready(function () {
$('.dates li a').click(function (e) {
$('.dates li a').removeClass('active');
var $parent = $(this);
if (!$parent.hasClass('active')) {
$parent.addClass('active');
}
e.preventDefault();
});
});
You can simply use
<a href="directry/filename.html#section5" >click me</a>
to link to a section/id of another page by
In MSSQL, this could be the way:
select distinct city from station
where
right(city,1) in ('a', 'e', 'i', 'o','u') and left(city,1) in ('a', 'e', 'i', 'o','u')
I'm seeing this a bit too often lately. Just today I had the issue with a class in the same package as the affected (red-flagged) class !
Exiting eclipse and restarting generally works to resolve the red flag on the affected class but sometimes a red flag is left on the project, then I also need to close the project and reopen it as well to get rid of the standalone red flag. It looks quite weird to see a red flag on a project, with no red flags in any of its child directories.
With maven project clusters, I close and open all of the projects in the cluster after restarting eclipse.
So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select
Where i
is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()
Dim Col1 As Integer
Dim Col2 As Integer
Col1 = 2
Col2 = 4
Range(Cells(1, Col1), Cells(1, Col2)).Select
End Sub
I use a swift extension like this:
extension UIWebView {
var htmlContent:String? {
return self.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
}
}
You could use cursor.lastrowid (see "Optional DB API Extensions"):
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
username varchar(50),
password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('test','test'))
print(cursor.lastrowid)
# 1
If two people are inserting at the same time, as long as they are using different cursor
s, cursor.lastrowid
will return the id
for the last row that cursor
inserted:
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
('blah','blah'))
print(cursor2.lastrowid)
# 3
print(cursor.lastrowid)
# 2
cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
(100,'blah','blah'))
print(cursor.lastrowid)
# 100
Note that lastrowid
returns None
when you insert more than one row at a time with executemany
:
cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
(('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None
I've seen some suggestions like having the image directory being a symbolic link pointing to a directory outside the web container, but will this approach work both on Windows and *nix environments?
If you adhere the *nix filesystem path rules (i.e. you use exclusively forward slashes as in /path/to/files
), then it will work on Windows as well without the need to fiddle around with ugly File.separator
string-concatenations. It would however only be scanned on the same working disk as from where this command is been invoked. So if Tomcat is for example installed on C:
then the /path/to/files
would actually point to C:\path\to\files
.
If the files are all located outside the webapp, and you want to have Tomcat's DefaultServlet
to handle them, then all you basically need to do in Tomcat is to add the following Context element to /conf/server.xml
inside <Host>
tag:
<Context docBase="/path/to/files" path="/files" />
This way they'll be accessible through http://example.com/files/...
. For Tomcat-based servers such as JBoss EAP 6.x or older, the approach is basically the same, see also here. GlassFish/Payara configuration example can be found here and WildFly configuration example can be found here.
If you want to have control over reading/writing files yourself, then you need to create a Servlet
for this which basically just gets an InputStream
of the file in flavor of for example FileInputStream
and writes it to the OutputStream
of the HttpServletResponse
.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Here's a basic example of such a servlet:
@WebServlet("/files/*")
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
File file = new File("/path/to/files", filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
When mapped on an url-pattern
of for example /files/*
, then you can call it by http://example.com/files/image.png
. This way you can have more control over the requests than the DefaultServlet
does, such as providing a default image (i.e. if (!file.exists()) file = new File("/path/to/files", "404.gif")
or so). Also using the request.getPathInfo()
is preferred above request.getParameter()
because it is more SEO friendly and otherwise IE won't pick the correct filename during Save As.
You can reuse the same logic for serving files from database. Simply replace new FileInputStream()
by ResultSet#getInputStream()
.
Hope this helps.
Use the Out-File
cmdlet
Compare-Object ... | Out-File C:\filename.txt
Optionally, add -Encoding utf8
to Out-File
as the default encoding is not really ideal for many uses.
Here is a simple way without stragg or creating a function.
create table countries ( country_name varchar2 (100));
insert into countries values ('Albania');
insert into countries values ('Andorra');
insert into countries values ('Antigua');
SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
COUNT (*) OVER () cnt
FROM countries)
WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;
CSV
--------------------------
Albania,Andorra,Antigua
1 row selected.
As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.
select listagg(country_name,', ') within group(order by country_name) csv
from countries;
CSV
--------------------------
Albania, Andorra, Antigua
1 row selected.
You can also use the pre-encoded HTML entity for a line break
in your content and it'll have the same effect.
Maybe you want unpack elements of array, I don't know if I got it, but below a example:
def my_func(*args):
for a in args:
print a
my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)
You cannot store arrays in a vector
or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.
You can, however, use an array
class template, like the one provided by Boost, TR1, and C++0x:
std::vector<std::array<double, 4> >
(You'll want to replace std::array
with std::tr1::array
to use the template included in C++ TR1, or boost::array
to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)
You may have accidentally cloned the repository in https instead of ssh. I've made this mistake numerous times on github. Make sure that you copy the ssh link in the first place when cloning, instead of the https link.
For anyone who looks at this today after 2 years, Visual Studio 2019 (Community edition as well) shows the references
If you don't need the model to update with every key-stroke, just bind to name
and then update the array item on blur event:
<div ng-repeat="name in names">
Value: {{name}}
<input ng-model="name" ng-blur="names[$index] = name" />
</div>
Simple object hasher:
(function () {
Number.prototype.toHex = function () {
var ret = ((this<0?0x8:0)+((this >> 28) & 0x7)).toString(16) + (this & 0xfffffff).toString(16);
while (ret.length < 8) ret = '0'+ret;
return ret;
};
Object.hashCode = function hashCode(o, l) {
l = l || 2;
var i, c, r = [];
for (i=0; i<l; i++)
r.push(i*268803292);
function stringify(o) {
var i,r;
if (o === null) return 'n';
if (o === true) return 't';
if (o === false) return 'f';
if (o instanceof Date) return 'd:'+(0+o);
i=typeof o;
if (i === 'string') return 's:'+o.replace(/([\\\\;])/g,'\\$1');
if (i === 'number') return 'n:'+o;
if (o instanceof Function) return 'm:'+o.toString().replace(/([\\\\;])/g,'\\$1');
if (o instanceof Array) {
r=[];
for (i=0; i<o.length; i++)
r.push(stringify(o[i]));
return 'a:'+r.join(';');
}
r=[];
for (i in o) {
r.push(i+':'+stringify(o[i]))
}
return 'o:'+r.join(';');
}
o = stringify(o);
for (i=0; i<o.length; i++) {
for (c=0; c<r.length; c++) {
r[c] = (r[c] << 13)-(r[c] >> 19);
r[c] += o.charCodeAt(i) << (r[c] % 24);
r[c] = r[c] & r[c];
}
}
for (i=0; i<r.length; i++) {
r[i] = r[i].toHex();
}
return r.join('');
}
}());
The meat here is the stringifier, which simply converts any object into a unique string. hashCode then runs over the object, hashing together the characters of the stringified object.
For extra points, export the stringifier and create a parser.
In the custom validation method use:
errors.add(:base, "Custom error message")
as add_to_base has been deprecated.
errors.add_to_base("Custom error message")
However -just for the record- this is invalid:
<address class="vcard">
<svg viewBox="0 0 800 400">
<rect width="800" height="400" fill="#000">
</svg>
</address>
And a slash here would make it valid again:
<rect width="800" height="400" fill="#000"/>
Use libraries https://jar-download.com/maven-repository-class-search.php?search_box=org.apache.http.entity.mime Download the library and put it in your project
yum install python34-pip
pip3.4 install foo
You will likely need the EPEL repositories installed:
yum install -y epel-release
You need module.exports:
Exports
An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.
For example, if you would like to expose variableName
with value "variableValue"
on sourceFile.js
then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...)
it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName
then
const variableName = 'variableValue'
module.exports = variableName
const variableName = require('./sourceFile')
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
--experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
- Files ending in
.mjs
.
.js
when the nearest parent package.json
file contains a top-level field "type"
with a value of "module"
.--eval
or --print
, or piped to node via STDIN, with the flag --input-type=module
.Once you have it setup, you can use import
and export
.
Using the example above, there are two approaches you can take
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
I was facing similar issue on my mac, and I found that docker wasn't running in my machine, I just went to applications and invoked whale and then it worked .
I find the following most elegant:
b = np.insert(a, 3, values=0, axis=1) # Insert values before column 3
An advantage of insert
is that it also allows you to insert columns (or rows) at other places inside the array. Also instead of inserting a single value you can easily insert a whole vector, for instance duplicate the last column:
b = np.insert(a, insert_index, values=a[:,2], axis=1)
Which leads to:
array([[1, 2, 3, 3],
[2, 3, 4, 4]])
For the timing, insert
might be slower than JoshAdel's solution:
In [1]: N = 10
In [2]: a = np.random.rand(N,N)
In [3]: %timeit b = np.hstack((a, np.zeros((a.shape[0], 1))))
100000 loops, best of 3: 7.5 µs per loop
In [4]: %timeit b = np.zeros((a.shape[0], a.shape[1]+1)); b[:,:-1] = a
100000 loops, best of 3: 2.17 µs per loop
In [5]: %timeit b = np.insert(a, 3, values=0, axis=1)
100000 loops, best of 3: 10.2 µs per loop
As somebody else mentioned, first you need react-router
package. But location
object that it provides you with contains parsed url.
But if you want full url badly without accessing global variables, I believe the fastest way to do that would be
...
const getA = memoize(() => document.createElement('a'));
const getCleanA = () => Object.assign(getA(), { href: '' });
const MyComponent = ({ location }) => {
const { href } = Object.assign(getCleanA(), location);
...
href
is the one containing a full url.
For memoize
I usually use lodash
, it's implemented that way mostly to avoid creating new element without necessity.
P.S.: Of course is you're not restricted by ancient browsers you might want to try new URL()
thing, but basically entire situation is more or less pointless, because you access global variable in one or another way. So why not to use window.location.href
instead?
Here's a function that will work for any Container:
template <class Container>
const bool contains(const Container& container, const typename Container::value_type& element)
{
return std::find(container.begin(), container.end(), element) != container.end();
}
Note that you can get away with 1 template parameter because you can extract the value_type
from the Container. You need the typename
because Container::value_type
is a dependent name.
If you have a parent container with vertical padding and you want something (e.g. an image) inside that container to ignore its vertical padding you can set a negative, but equal, margin for both 'top' and 'bottom':
margin-top: -100px;
margin-bottom: -100px;
The actual value doesn't appear to matter much. Haven't tried this for horizontal paddings.
Pros and cons between #define
s, const
s and (what you have forgot) enum
s, depending on usage:
enum
s:
enum class X
are disambiguated by the scope X::
int
but can be explicitly set by the programmertemplate <typename T> void f(T t) { cout << ++t; }
won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)template <typename T> void f(T)
get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int)
instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.enum { A = 1, B = 2 }
- is A|B
"legal" from a program logic perspective?)make
and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)const
s:
#define
ala #define S std::string("abc")
, but the constant avoids repeated construction of distinct temporaries at each point of useconst
value, which minimises work and impact if switching between the two#define
s:
#define X "x"
and some client usage ala "pre" X "post"
, if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char*
or const std::string
given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post"
for string
)sizeof
directly on a defined numeric literalunsigned
){ 1, 2 }
that can be used to initialise arrays, or #define MICROSECONDS *1E-6
etc. (definitely not recommending this!)__FILE__
and __LINE__
can be incorporated into the macro substitution#if
statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef
-ine, redefine etc.make
and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)My personal opinion:
As a general rule, I use const
s and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).
You can disable the background's click-to-close behavior and make this the default for all your modals by adding this JavaScript to your page (make sure it is executed after jQuery and Bootstrap JS are loaded):
$(function() {
$.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
});
To get bits per pixel:
import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);
screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
parameters in gdi32:
#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,
Static Read Only:
The value can be changed through a static
constructor at runtime. But not through a member function.
Constant:
By default static
. A value cannot be changed from anywhere (constructor, function, runtime, etc. nowhere).
Read Only:
The value can be changed through a constructor at runtime. But not through a member function.
You can have a look at my repository: C# property types.
Simply:
grep 'word1\|word2\|word3' *
see this post for more info
In my apache server, this gives me the full URL in the exact format you are looking for:
$_SERVER["SCRIPT_URI"]
If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.
x.astype('float')
before round(...).
All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.
Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.
You can find the current user name with CURRENT_USER() function in MySQL.
for Ex:
SELECT CURRENT_USER();
But CURRENT_USER()
will not always return the logged in user. So in case you want to have the logged in user, then use SESSION_USER()
instead.
Please ensure you have installed MySQL server correctly, I met this error many times and I think it's complicated to debug from the socket, I mean it might be easier to reinstall it.
If you are using CentOS 7, here is the correct way to install it:
First of all, add the mysql community source
yum install http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
Then you can install it by yum install mysql-community-server
Start it with systemctl: systemctl start mysqld
While these answers are technically correct, including Ushox, I think the approved way is to implement a new protocol or re-use an existing one. A protocol insulates the observer from the observed, sort of like putting a mail slot in between them. In effect, that is what Gabriel does via the pushViewController method invocation; the view "knows" that it is proper protocol to politely ask your navigationController to push a view, since the viewController conforms to the navigationController protocol. While you can create your own protocol, just using Gabriel's example and re-using the UINavigationController protocol is just fine.
You still can run it from File explorer on Windows 10 with the proper path. You just need to go to C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
and double click the file monitor.
If you want to use in the cmd just the 'monitor' command you have to add this folder (in my case with android studio 3.4.1 and win10) to your Environment variables. So, press the start button and then type Edit the system environment variabes
click it and System properties window should open. Then go to
Environment variables => System variables => path
press the Edit
button for path and add the new value
C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64
click 'Ok', 'Ok' and 'Ok' and restart the cmd window if you had it opened and type 'monitor' and it should open the monitor as well.
Hope it helps!
PD: This answer was based on this answer https://stackoverflow.com/a/55077068/5360905 from Tiago Martins Peres
Most simple way in explorer is to Shift + right mouse click on the folder or on an empty space in the folder and click on Open command prompt here
.
CMD will then start in that folder
I must say, I'm not sure if it works for Windows Vista and below, but it surely works for Windows 7, 8, 8.1 and 10.
FYI, for the cases where your page is loading with other javascript libraries like mootools that are conflicting with the $
symbol, you can use jQuery
instead.
For instance, jQuery.fn.jquery
or jQuery().jquery
would work just fine:
With jQuery's validation plugin you could do something like this, assuming that the form is called form and the value to validate is called nrInput
$("form").validate({
errorElement: "div",
errorClass: "error-highlight",
onblur: true,
onsubmit: true,
focusInvalid: true,
rules:{
'nrInput': {
number: true,
required: true
}
});
This also handles decimal values.
From the mysql
man page:
You can execute SQL statements in a script file (batch file) like this:
shell> mysql db_name < script.sql > output.tab
Put the query in script.sql
and run it.
Look in the MySQL config file C:\xampp\mysql\bin\my.ini
.
At the top of that file are some comments:
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
There it tells you where to find your .my.cnf
file.
Another option would be to simply use grepl
function:
df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]
df <- data.frame(name = c('bob','robert','peter'),
id = c(1,2,3)
)
# name id
# 2 robert 2
# 3 peter 3
Just comment out the whole "User for advanced features" and "Advanced phpMyAdmin features" code blocks in config.inc.php
.
Well, unfortunately it seems that one cannot place custom markers and draw (and obtain coordinates) directly from maps.google.com if one is anonymous/not logged in (as it was possible some years ago, if I recall correctly). Still, thanks to the answers here, I managed to make a combination of examples that has both the Google Places search, and allows drawing via the drawing library, and dumps coordinates upon making a selection of any type of shape (including coordinates for polygon) that can be copypasted; the code is here:
This is how it looks like:
(The Places markers are handled separately, and can be deleted via the DEL "button" by the search input form element; "curpos" shows the current center [position] and zoom level of the map viewport).
http://jsbin.com/qamuyajipo/3/edit?html,output
.circle {
border: 1px solid red;
background-color: #FFFFFF;
height: 100px;
-moz-border-radius:75px;
-webkit-border-radius: 75px;
width: 100px;
}
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
This one drove me completely insane and I couldn't find anything helpful to solve it. This is probably not the reason most people have this issue but I just hope that someone else will benefit from this answer.
What caused my problem was a <clear />
statement in the <assemblies>
config section. I had added this because in production it had been required because there were multiple unrelated applications on the same hosting plan and I didn't want any of them to be affected by others. The more correct solution would have been to have just used web config transforms on publish.
Hope this helps someone else!
I found that it's easy to write an app that can open another app.
Let's assume that we have two apps called FirstApp
and SecondApp
. When we open the FirstApp, we want to be able to open the SecondApp by clicking a button. The solution to do this is:
In SecondApp
Go to the plist file of SecondApp and you need to add a URL Schemes with a string iOSDevTips(of course you can write another string.it's up to you).
2 . In FirstApp
Create a button with the below action:
- (void)buttonPressed:(UIButton *)button
{
NSString *customURL = @"iOSDevTips://";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
message:[NSString stringWithFormat:@"No custom URL defined for %@", customURL]
delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
}
That's it. Now when you can click the button in the FirstApp it should open the SecondApp.
It would look like this:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
If the constants are for use just in a single class, you'd want to make them private
instead of public
.
git gui provides this functionality under the diff view. Just right click the line(s) you're interested in and you should see a "stage this line to commit" menu item.
You can use wsdlrdr also. EasySoap is basically rewrite of wsdlrdr with some extra methods. Be careful that easysoap doesn't have the getNamespace method which is available at wsdlrdr.
Easy way:
Open the file bootstrap-datepicker.js
Go to line 1399 and find format: 'mm/dd/yyyy'
.
Now you can change the date format here.
Just use a onchnage Event
for select box.
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.yahoo.com/" selected>Option1</option>
<option value="https://www.google.co.in/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
And if selected option to be loaded at the page load then add some javascript code
<script type="text/javascript">
window.onload = function(){
location.href=document.getElementById("selectbox").value;
}
</script>
for jQuery: Remove the onchange event from <select>
tag
jQuery(function () {
// remove the below comment in case you need chnage on document ready
// location.href=jQuery("#selectbox").val();
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
And a code example:
<div ng-app>
<div ng-controller="FooController">
<ul ng-repeat="item in items | orderBy:'num':true">
<li>{{item.num}} :: {{item.desc}}</li>
</ul>
</div>
</div>
And the JavaScript:
function FooController($scope) {
$scope.items = [
{desc: 'a', num: 1},
{desc: 'b', num: 2},
{desc: 'c', num: 3},
];
}
Will give you:
3 :: c
2 :: b
1 :: a
On JSFiddle: http://jsfiddle.net/agjqN/
vcvarsall.bat
is part of the Visual C++ compiler, you need that to install what you are trying to install. Don't even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the version of the Microsoft tool chain is important. Python compiled with VS 2008 won't work with extensions compiled with VS 2010!
You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for "Unable to find vcvarsall.bat" because that is the root of your problem, it is a very common problem with compiling Python extensions on Windows.
As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.
Be careful if you do this. Python 2.6 and 2.7 from python.org are built with Visual Studio 2008 compilers. You will need to link with the same CRT (msvcr90.dll) as Python.
Visual Studio 2010 Express links with the wrong CRT version: msvcr100.dll.
If you do this, you must also re-build Python with Visual Studio 2010 Express. You cannot use the standard Python binary installer for Windows. Nor can you use any C/C++ extensions built with a different compiler than Visual Studio 2010 (Express).
Opinion: This is one reason I abandoned Windows for all serious development work for OSX!
To exit hitting :q will let you quit.
If you want to quit without saving you can hit :q!
A google search on "vim cheatsheet" can provide you with a reference you should print out with a collection of quick shortcuts.
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
If you only want to perform some specific operations by your second SP and do not require values back from the SP then simply do:
Exec secondSPName @anyparams
Else, if you need values returned by your second SP inside your first one, then create a temporary table variable with equal numbers of columns and with same definition of column return by second SP. Then you can get these values in first SP as:
Insert into @tep_table
Exec secondSPName @anyparams
Update:
To pass parameter to second sp, do this:
Declare @id ID_Column_datatype
Set @id=(Select id from table_1 Where yourconditions)
Exec secondSPName @id
Update 2:
Suppose your second sp returns Id
and Name
where type of id
is int
and name
is of varchar(64)
type.
now, if you want to select these values in first sp then create a temporary table
variable and insert values into it:
Declare @tep_table table
(
Id int,
Name varchar(64)
)
Insert into @tep_table
Exec secondSP
Select * From @tep_table
This will return you the values returned by second SP.
Hope, this clear all your doubts.
You don't need a for loop in your code.
Here is how you can re implement your method
Edit:
Here is hint for you to proceed, Following code snippet gives int
values for char
s
System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');
Output
a=97
z=122
A=65
Z=90
Here is how you can check if a number x
exists between two numbers say a
and b
// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b )
During comparisons char
s can be treated as numbers
If you can combine these hints, you should be able to find what you want ;)
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.
You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:
onchange="this.form.submit()"
Example:
<form>
<div>
<input type="checkbox">
</div>
</form>
Sometime only this helps:
View child = parent.findViewById(R.id.btnMoreText);
child.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View parent = (View) v.getParent();
parent.performClick();
}
});
Another variant, works not always:
child.setOnClickListener(null);
XCode 12 update:
If you run xcodebuild
without -arch
param, XCode 12 will build simulator library with architecture "arm64 x86_64" as default.
Then run xcrun -sdk iphoneos lipo -create -output
will conflict, because arm64
architecture exist in simulator and also device library.
I fork script from Adam git and fix it.
A key issue here is that this loop iterates over the rows (1st dimension) of B
:
In [258]: B
Out[258]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [259]: for b in B:
...: print(b,'=>',end='')
...: b += 1
...: print(b)
...:
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]
Thus the +=
is acting on a mutable object, an array.
This is implied in the other answers, but easily missed if your focus is on the a = a+1
reassignment.
I could also make an in-place change to b
with [:]
indexing, or even something fancier, b[1:]=0
:
In [260]: for b in B:
...: print(b,'=>',end='')
...: b[:] = b * 2
[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]
Of course with a 2d array like B
we usually don't need to iterate on the rows. Many operations that work on a single of B
also work on the whole thing. B += 1
, B[1:] = 0
, etc.
The video quality depends upon the Connection speed using API
alternatively for other than API means without YouTube app you can follow this link
You could tell wget to not download the contents in a couple of different ways:
wget --spider http://www.example.com/cronit.php
which will just perform a HEAD request but probably do what you want
wget -O /dev/null http://www.example.com/cronit.php
which will save the output to /dev/null (a black hole)
You might want to look at wget's -q switch too which prevents it from creating output
I think that the best option would probably be:
wget -q --spider http://www.example.com/cronit.php
that's unless you have some special logic checking the HTTP method used to request the page
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
LibGDX is one of the best engines I've ever used, works on almost all platforms, and performs twice as fast as cocos2d-x in most tests I've done. You can use any JVM language you like. Here's a 13 part tutorial in Java, and here's a bunch using jruby. There's a good skeletal animation tool that works with it here, and it has baked in support for tiled TMX maps as well. The ui framework is awesome, and it has a scene graph and actor style API similar to cocos2d scenes, sprites and actions. The community is awesome, updates are frequent, and the documentation is good. Don't let the java part scare you, it's fast, and you can use jruby or scala or whatever you like. I highly recommend it for 2d or 3d work, it supports both.
A boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming, as in “boilerplate code
When I use SourceTree to do the stuff, it will spit out this message.
The message that I encountered:
git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree submodule update --init --recursive
No submodule mapping found in .gitmodules for path 'SampleProject/SampleProject'
Completed with errors, see above
My scenario is I misapplied the project directory the contains .git folder.
SourceTree regarded this folder as git submodule, but actually not.
My solution is use command line to remove it.
$ git rm -r SampleProject --cached
$ git commit -m "clean up folders"
remove the garbage in git and keep it clean.
Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel
then you can do it in two ways:
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
or
DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
dm.removeRow(0);
}
See the JavaDoc of DefaultTableModel for more details
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
If I get 'someObject', say via
someObject <- myMagicFunction(...)
then I usually proceed by
class(someObject)
str(someObject)
which can be followed by head(), summary(), print(), ... depending on the class you have.
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your html
html_safe
sets a boolean in string so that the string is considered as html save
raw
It converts to html_safe to string
Also, you can use bool method(s)
Query :
DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
where isValid(Field<string>("UserName"))// && otherMethod() && otherMethod2()
select r;
DataTable newDT = query.CopyToDataTable();
Method:
bool isValid(string userName)
{
if(userName == "XXXX" || userName == "YYYY")
return false;
else return true;
}
The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.
The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.
Before you start you will need some information:
<package name>
, for example, com.example.application
<local path>
to place your database, eg. ~/Desktop
or %userprofile%\Desktop
Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:
>
= you OS command prompt$
= ADB shell command Prompt!
= ADB shell as admin command prompt%
Next enter the following commands from Terminal or Command (don't enter first character or text in ()
)
> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit (to exit sqldb)
This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.
If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
The standard way of using merge to undo the entire check-in works great, if that's what you want to do. Sometimes, though, all you want to do is revert a single file. There's no legitimate way to do that, but there is a hack:
Use svn's export subcommand:
svn export http://url-to-your-file@123 /tmp/filename
(Where 123 is the revision number for a good version of the file.) Then either move or copy that single file to overwrite the old one. Check in the modified file and you are done.
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;
df.reset_index(drop=True, inplace=True)
As explained here, you can use:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!
I managed to hit this error when simply creating a table! There was obviously no contention problem on a table that didn't yet exist. The CREATE TABLE
statement contained a CONSTRAINT fk_name FOREIGN KEY
clause referencing a well-populated table. I had to:
Use
Model.created_at.strftime("%FT%T")
where,
%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)
Following are some of the frequently used useful list of Date
and Time
formats that you could specify in strftime
method:
Date (Year, Month, Day):
%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%C - year / 100 (round down. 20 in 2009)
%y - year % 100 (00..99)
%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%B - The full month name (``January'')
%^B uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
%^b uppercased (``JAN'')
%h - Equivalent to %b
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)
%j - Day of the year (001..366)
Time (Hour, Minute, Second, Subsecond):
%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)
%l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')
%M - Minute of the hour (00..59)
%S - Second of the minute (00..59)
%L - Millisecond of the second (000..999)
%N - Fractional seconds digits, default is 9 digits (nanosecond)
%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
%12N picosecond (12 digits)
For the complete list of formats for strftime
method please visit APIDock
might want to try something as simple as below in the command line:
sed -n '$=' filename
or
wc -l filename
Probably you haven't injected $http
service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
var elems = document.querySelectorAll('.one');_x000D_
_x000D_
for (var i = 0; i < elems.length; i++) {_x000D_
elems[i].innerHTML = 'content';_x000D_
};
_x000D_
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
If there is already a nbproject folder it means you can open it straight ahead without importing it as a project with existing sources (ctrl+shift+o) or (cmd+shift+o)
I have the same issue and I change any hostname that matches the local host name to 0.0.0.0, it seems to work after I do that.
fastest way is by signing with the debug keystore:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android
or on Windows:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android
Try:
SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name
public String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
We can do that with two way:
1- First create a new object and replicate the structure of the existing one by iterating
over its properties and copying them on the primitive level.
let user = {
name: "John",
age: 30
};
let clone = {}; // the new empty object
// let's copy all user properties into it
for (let key in user) {
clone[key] = user[key];
}
// now clone is a fully independant clone
clone.name = "Pete"; // changed the data in it
alert( user.name ); // still John in the original object
2- Second we can use the method Object.assign for that
let user = { name: "John" };
let permissions1 = { canView: true };
let permissions2 = { canEdit: true };
// copies all properties from permissions1 and permissions2 into user
Object.assign(user, permissions1, permissions2);
-Another example
let user = {
name: "John",
age: 30
};
let clone = Object.assign({}, user);
It copies all properties of user into the empty object and returns it. Actually, the same as the loop, but shorter.
But Object.assign() not create a deep clone
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
alert( user.sizes === clone.sizes ); // true, same object
// user and clone share sizes
user.sizes.width++; // change a property from one place
alert(clone.sizes.width); // 51, see the result from the other one
To fix that, we should use the cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.
There’s a standard algorithm for deep cloning that handles the case above and more complex cases, called the Structured cloning algorithm. In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library lodash the method is called _.cloneDeep(obj).
Have you checked this http://support.microsoft.com/kb/209805? In particular, whether you have Msrd3x40.dll.
You may also like to check that you have the latest version of Jet: http://support.microsoft.com/kb/239114
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
Executive summary:
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
To determine the size of your array in bytes, you can use the sizeof
operator:
int a[17];
size_t n = sizeof(a);
On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this:
int a[17];
size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type of
a
changed you would have a nasty bug if you forgot to change
the sizeof(int)
as well.
So the preferred divisor is sizeof(a[0])
or the equivalent sizeof(*a)
, the size of the first element of the array.
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
from Google
An .axd file is a HTTP Handler file. There are two types of .axd files.
These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.
Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere
And ofcourse it is necessary
Here is my answer:
services.msc
, Enter"D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56
Full answer here: https://stackoverflow.com/a/20136523/1316649
You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project
I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.
Set.of(CustomType.values())
.contains(customTypevalue)
Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Use a Func<T1, T2, TResult>
delegate as the parameter type and pass it in to your Query
:
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
You would call it:
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
Or assign the lambda to a variable and pass it in.
ExecuteScalar will return
If you know that the first column of the resultset is a string, then to cover all bases you need to check for both null and DBNull. Something like:
object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null) ? String.Empty : accountNumber.ToString();
The above code relies on the fact that DBNull.ToString returns an empty string.
If accountNumber was another type (say integer), then you'd need to be more explicit:
object accountNumber = ...ExecuteScalar(...);
return (accountNumber == null || Convert.IsDBNull(accountNumber) ?
(int) accountNumber : 0;
If you know for sure that your resultset will always have at least one row (e.g. SELECT COUNT(*)...), then you can skip the check for null.
In your case the error message "Unable to cast object of type ‘System.DBNull’ to type ‘System.String`" indicates that the first column of your result set is a DBNUll value. This is from the cast to string on the first line:
string accountNumber = (string) ... ExecuteScalar(...);
Marc_s's comment that you don't need to check for DBNull.Value is wrong.
In order to completely override the bootstrap button styles, you need to override a list of properties. See the below example.
.btn-primary, .btn-primary:hover, .btn-primary:focus, .btn-primary.focus,
.btn-primary:active, .btn-primary.active, .btn-primary:visited,
.btn-primary:active:hover, .btn-primary.active:hover{
background-color: #F19425;
color:#fff;
border: none;
outline: none;
}
If you don't use all the listed styles then you will see the default styles at performing actions on button. For example once you click the button and remove mouse pointer from button, you will see the default color visible. Or keep the button pressed you will see default colors. So, I have listed all the pseudo-styles that are to be overridden.
To clarify, yes, you need to set default values in the constructor for class derived objects. You will need to ensure the constructor exists with the proper access modifier for construction where used. If the object is not instantiated, e.g. it has no constructor (e.g. static methods) then the default value can be set by the field. The reasoning here is that the object itself will be created only once and you do not instantiate it.
@Darren Kopp - good answer, clean, and correct. And to reiterate, you CAN write constructors for Abstract methods. You just need to access them from the base class when writing the constructor:
Constructor at Base Class:
public BaseClassAbstract()
{
this.PropertyName = "Default Name";
}
Constructor at Derived / Concrete / Sub-Class:
public SubClass() : base() { }
The point here is that the instance variable drawn from the base class may bury your base field name. Setting the current instantiated object value using "this." will allow you to correctly form your object with respect to the current instance and required permission levels (access modifiers) where you are instantiating it.
I had this problem while writing VB in an aspx
page.
The solution was to go to 'Tools > Options > Text Editor > Basic > VB Specific' and turn 'Pretty Listing' OFF.
Note - in Visual Studio 2015 this can be found at:
Tools > Options > Text Editor > Basic > Advanced
Set editable
to False
and default
to your default value.
http://docs.djangoproject.com/en/stable/ref/models/fields/#editable
b = models.CharField(max_length=7, default='0000000', editable=False)
Also, your id
field is unnecessary. Django will add it automatically.
I know that there are already many answers but for the sake of simplicity i would like to add another answer which is simple and self explanatory in which we do not have to remember keycodes and it also works across all browsers.
document.getElementById('myinput').onkeydown = function(e)_x000D_
{_x000D_
console.log(e.key);_x000D_
//console.log(e.target.value);_x000D_
switch (e.key)_x000D_
{_x000D_
case "1":_x000D_
case "2":_x000D_
case "3":_x000D_
case "4":_x000D_
case "5":_x000D_
case "6":_x000D_
case "7":_x000D_
case "8":_x000D_
case "9":_x000D_
case "0":_x000D_
case "Backspace":_x000D_
return true;_x000D_
break;_x000D_
_x000D_
case ".":_x000D_
if (e.target.value.indexOf(".") == -1)_x000D_
{_x000D_
return true;_x000D_
}_x000D_
else_x000D_
{_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
_x000D_
default:_x000D_
return false;_x000D_
}_x000D_
_x000D_
}
_x000D_
<input type="text" placeholder="Enter Value" id="myinput" />
_x000D_
In my case i had some problem with opacity transition so this one fix it:
#dropdown {
transition:.6s opacity;
}
#dropdown.ns {
opacity:0;
transition:.6s all;
}
#dropdown.fade {
opacity:1;
}
Mouse Enter
$('#dropdown').removeClass('ns').addClass('fade');
Mouse Leave
$('#dropdown').addClass('ns').removeClass('fade');
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
@inoabrian solution above worked for me. I ran into a situation where I would refresh my page and my hidden element would reappear on my page. Here's what I did to resolve it.
export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;
ngOnInit() {
if (condition is true) {
this.showJoinTodayBtn = true;
} else {
this.showJoinTodayBtn = false;
}
}
Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.
I have actually found the proper solution and posted it under almost the same question here. For more details head there.
Solution:
# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo
Since Java 13 you have formatted
1 method on String, which was added along with text blocks as a preview feature 2.
You can use it instead of String.format()
Assertions.assertEquals(
"%s %d %.3f".formatted("foo", 123, 7.89),
"foo 123 7.890"
);
Gravity is used to set text alignment in views but layout_gravity is use to set views it self. Lets take an example if you want to align text written in editText then use gravity and you want align this editText or any button or any view then use layout_gravity, So its very simple.
I have also one solution. I always use this method. Try this
<ScrollView
android:id="@+id/createdrill_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp" >
<net.thepaksoft.fdtrainer.NestedListView
android:id="@+id/crewList"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_weight="1"
android:background="@drawable/round_shape"
android:cacheColorHint="#00000000" >
</net.thepaksoft.fdtrainer.NestedListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp" >
<net.thepaksoft.fdtrainer.NestedListView
android:id="@+id/benchmarksList"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_weight="1"
android:background="@drawable/round_shape"
android:cacheColorHint="#00000000" >
</net.thepaksoft.fdtrainer.NestedListView>
</LinearLayout>
</ScrollView>
NestedListView.java class:
public class NestedListView extends ListView implements OnTouchListener, OnScrollListener {
private int listViewTouchAction;
private static final int MAXIMUM_LIST_ITEMS_VIEWABLE = 99;
public NestedListView(Context context, AttributeSet attrs) {
super(context, attrs);
listViewTouchAction = -1;
setOnScrollListener(this);
setOnTouchListener(this);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
scrollBy(0, -1);
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int newHeight = 0;
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
ListAdapter listAdapter = getAdapter();
if (listAdapter != null && !listAdapter.isEmpty()) {
int listPosition = 0;
for (listPosition = 0; listPosition < listAdapter.getCount()
&& listPosition < MAXIMUM_LIST_ITEMS_VIEWABLE; listPosition++) {
View listItem = listAdapter.getView(listPosition, null, this);
//now it will not throw a NPE if listItem is a ViewGroup instance
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
listItem.measure(widthMeasureSpec, heightMeasureSpec);
newHeight += listItem.getMeasuredHeight();
}
newHeight += getDividerHeight() * listPosition;
}
if ((heightMode == MeasureSpec.AT_MOST) && (newHeight > heightSize)) {
if (newHeight > heightSize) {
newHeight = heightSize;
}
}
} else {
newHeight = getMeasuredHeight();
}
setMeasuredDimension(getMeasuredWidth(), newHeight);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (getAdapter() != null && getAdapter().getCount() > MAXIMUM_LIST_ITEMS_VIEWABLE) {
if (listViewTouchAction == MotionEvent.ACTION_MOVE) {
scrollBy(0, 1);
}
}
return false;
}
}
Missing driver file.
This error is really common for people just getting started with PDI.
Drivers go in \pentaho\design-tools\data-integration\libext\JDBC for PDI. If you are using other tools in the Pentaho suite, you may need to copy drivers to additional locations for those tools. For reference, here are the appropriate folders for some of the other design tools:
If this transformation or job will run on another box, such as a test or production server, don't forget to include copying the jar file and restarting PDI or the Data Integration Server in your deployment considerations.
The question is about a non rooted device but if it is rooted the simplest way would be to:
From the terminal on your phone, do this:
su
setprop service.adb.tcp.port 5555
stop adbd
start adbd
See this answer for full details.
Building on Will Shepard's answer, his output will include duplicate lines for commits where there was no change, so you can filter those as as follows (using this answer)
LINE=1 FILE=a; for commit in $(git rev-list HEAD $FILE); do git blame -n -L$LINE,+1 $commit -- $FILE; done | sed '$!N; /^\(.*\)\n\1$/!P; D'
Note that I removed the REVS argument and this goes back to the root commit. This is due to Max Nanasy's observation above.
If you just want to re-load/update dependencies (I assume, with constantly changing you mean either SNAPSHOTS or local dependencies you update yourself), you can use
mvn dependency:resolve
Heres the Swift version:
myButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
An alternative, using plain Java 7 classes and varargs: create a class HashMapBuilder
with this method:
public static HashMap<String, String> build(String... data){
HashMap<String, String> result = new HashMap<String, String>();
if(data.length % 2 != 0)
throw new IllegalArgumentException("Odd number of arguments");
String key = null;
Integer step = -1;
for(String value : data){
step++;
switch(step % 2){
case 0:
if(value == null)
throw new IllegalArgumentException("Null key value");
key = value;
continue;
case 1:
result.put(key, value);
break;
}
}
return result;
}
Use the method like this:
HashMap<String,String> data = HashMapBuilder.build("key1","value1","key2","value2");
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
Here I made a toggle button with CSS:
.switch {
position: relative;
display: inline-block;
width: 100%;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2ab934;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(165px);
-ms-transform: translateX(165px);
transform: translateX(200px);
}
/*------ ADDED CSS ---------*/
.on
{
display: none;
}
.on, .off
{
color: white;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked+ .slider .on
{display: block;}
input:checked + .slider .off
{display: none;}
/*--------- END --------*/
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;}
Here is the HTML code of toggle button with text:
<input type="checkbox" id="togBtn">
<div class="slider round">
<!--ADDED HTML -->
<span class="on">BOOKED</span>
<span class="off">AVAILABLE</span>
<!--END-->
</div>
There is a fairly well maintained repo on github that has a CSV (with semicolon delimiters), XML, and JSON source of countries, country codes, and other information.
Visually select the text and type:
ggVG
!tee >(pbcopy)
Which I find nicer than:
ggVG
:w !pbcopy
Since it doesn't flash up a prompt: "Press ENTER or type command to continue"
To create user in MySQL/MariaDB 5.7.6 and higher, use CREATE USER
syntax:
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';
then to grant all access to the database (e.g. my_db
), use GRANT
Syntax, e.g.
GRANT ALL ON my_db.* TO 'new_user'@'localhost';
Where ALL
(priv_type) can be replaced with specific privilege such as SELECT
, INSERT
, UPDATE
, ALTER
, etc.
Then to reload newly assigned permissions run:
FLUSH PRIVILEGES;
To run above commands, you need to run mysql
command and type them into prompt, then logout by quit
command or Ctrl-D.
To run from shell, use -e
parameter (replace SELECT 1
with one of above commands):
$ mysql -e "SELECT 1"
or print statement from the standard input:
$ echo "FOO STATEMENT" | mysql
If you've got Access denied with above, specify -u
(for user) and -p
(for password) parameters, or for long-term access set your credentials in ~/.my.cnf
, e.g.
[client]
user=root
password=root
For people not familiar with MySQL syntax, here are handy shell functions which are easy to remember and use (to use them, you need to load the shell functions included further down).
Here is example:
$ mysql-create-user admin mypass
| CREATE USER 'admin'@'localhost' IDENTIFIED BY 'mypass'
$ mysql-create-db foo
| CREATE DATABASE IF NOT EXISTS foo
$ mysql-grant-db admin foo
| GRANT ALL ON foo.* TO 'admin'@'localhost'
| FLUSH PRIVILEGES
$ mysql-show-grants admin
| SHOW GRANTS FOR 'admin'@'localhost'
| Grants for admin@localhost
| GRANT USAGE ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4' |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'admin'@'localhost'
$ mysql-drop-user admin
| DROP USER 'admin'@'localhost'
$ mysql-drop-db foo
| DROP DATABASE IF EXISTS foo
To use above commands, you need to copy&paste the following functions into your rc file (e.g. .bash_profile
) and reload your shell or source the file. In this case just type source .bash_profile
:
# Create user in MySQL/MariaDB.
mysql-create-user() {
[ -z "$2" ] && { echo "Usage: mysql-create-user (user) (password)"; return; }
mysql -ve "CREATE USER '$1'@'localhost' IDENTIFIED BY '$2'"
}
# Delete user from MySQL/MariaDB
mysql-drop-user() {
[ -z "$1" ] && { echo "Usage: mysql-drop-user (user)"; return; }
mysql -ve "DROP USER '$1'@'localhost';"
}
# Create new database in MySQL/MariaDB.
mysql-create-db() {
[ -z "$1" ] && { echo "Usage: mysql-create-db (db_name)"; return; }
mysql -ve "CREATE DATABASE IF NOT EXISTS $1"
}
# Drop database in MySQL/MariaDB.
mysql-drop-db() {
[ -z "$1" ] && { echo "Usage: mysql-drop-db (db_name)"; return; }
mysql -ve "DROP DATABASE IF EXISTS $1"
}
# Grant all permissions for user for given database.
mysql-grant-db() {
[ -z "$2" ] && { echo "Usage: mysql-grand-db (user) (database)"; return; }
mysql -ve "GRANT ALL ON $2.* TO '$1'@'localhost'"
mysql -ve "FLUSH PRIVILEGES"
}
# Show current user permissions.
mysql-show-grants() {
[ -z "$1" ] && { echo "Usage: mysql-show-grants (user)"; return; }
mysql -ve "SHOW GRANTS FOR '$1'@'localhost'"
}
Note: If you prefer to not leave trace (such as passwords) in your Bash history, check: How to prevent commands to show up in bash history?
a simple solution would be :
>>> df.groupby(['A','B']).c.unique().reset_index()
I can do like that (sorry it's c# not java but it's not a problem...) :
private int iValue = 1234567890;
function void MyTest()
{
Intent oIntent = new Intent (this, typeof(Camera2Activity));
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue); //=> 1234567890
oIntent.PutExtras (oBundle);
iRequestCode = 1111;
StartActivityForResult (oIntent, 1111);
}
AND IN YOUR ACTIVITY FOR RESULT
private int iValue = 0;
protected override void OnCreate(Bundle bundle)
{
Bundle oBundle = Intent.Extras;
if (oBundle != null)
{
iValue = oBundle.GetInt("MYVALUE", 0);
//=>1234567890
}
}
private void FinishActivity(bool bResult)
{
Intent oIntent = new Intent();
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue);//=>1234567890
oIntent.PutExtras(oBundle);
if (bResult)
{
SetResult (Result.Ok, oIntent);
}
else
SetResult(Result.Canceled, oIntent);
GC.Collect();
Finish();
}
FINALLY
protected override void OnActivityResult(int iRequestCode, Android.App.Result oResultCode, Intent oIntent)
{
base.OnActivityResult (iRequestCode, oResultCode, oIntent);
iValue = oIntent.Extras.GetInt("MYVALUE", -1); //=> 1234567890
}
Translated from here:
Dimension getScaledDimension(Dimension imageSize, Dimension boundary) {
double widthRatio = boundary.getWidth() / imageSize.getWidth();
double heightRatio = boundary.getHeight() / imageSize.getHeight();
double ratio = Math.min(widthRatio, heightRatio);
return new Dimension((int) (imageSize.width * ratio),
(int) (imageSize.height * ratio));
}
You can also use imgscalr to resize images while maintaining aspect ratio:
BufferedImage resizeMe = ImageIO.read(new File("orig.jpg"));
Dimension newMaxSize = new Dimension(255, 255);
BufferedImage resizedImg = Scalr.resize(resizeMe, Method.QUALITY,
newMaxSize.width, newMaxSize.height);
If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:
Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }
You can now easily access it like this: Object['sushi']['name']
Or if the object really is this simple (just 'name' in the object), you could just change it to:
Obj = { 'pizza' : 'bob', 'sushi' : 'john' }
And then access it like: Object['sushi']
.
It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.
if(DialogResult.OK==MessageBox.Show("Do you Agree with me???"))
{
//do stuff if yess
}
else
{
//do stuff if No
}
let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
self.showLoginError(error)
create an NSError object and typecast it to Error ,show it anywhere
private func showLoginError(_ error: Error?) {
if let errorObj = error {
UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
}
}
Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).
First create the file rewrite-log.load
/etc/apache2/mods-availabe/rewrite-log.load
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
Then enter
$ a2enmod rewrite-log
followed by
$ service apache2 restart
And when you finished with debuging your rewrite rules
$ a2dismod rewrite-log && service apache2 restart
moment(timestamp).format('''any format''')
May I recommend you corn-httpclient. It's simple,fast and enough for most cases.
HttpForm form = new HttpForm(new URI("http://localhost:8080/test/formtest.jsp"));
//Authentication form.setCredentials("user1", "password");
form.putFieldValue("input1", "your value");
HttpResponse response = form.doPost();
assertFalse(response.hasError());
assertNotNull(response.getData());
assertTrue(response.getData().contains("received " + val));
maven dependency
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-httpclient</artifactId>
<version>1.0.0</version>
</dependency>
This is new thing in C++ 0x standards where you can delete an inherited function.
if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.
You could always just set the width of each td to 100%/N columns.
<td width="x%"></td>
In Entity Framework 6.1+ you can use this attribute on your model:
[Index(IsUnique=true)]
You can find it in this namespace:
using System.ComponentModel.DataAnnotations.Schema;
If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:
Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.
The reason is because of this:
SQL Server retains the 900-byte limit for the maximum total size of all index key columns."
(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )
You can solve this by setting a maximum string length on your model:
[StringLength(450)]
Your model will look like this now in EF CF 6.1+:
public class User
{
public int UserId{get;set;}
[StringLength(450)]
[Index(IsUnique=true)]
public string UserName{get;set;}
}
Update:
if you use Fluent:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// ....
Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
}
}
and use in your modelBuilder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
modelBuilder.Configurations.Add(new UserMap());
// ...
}
Update 2
for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698
Update 3
for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274
Update 4
ASP.NET Core Mvc 2.2 with EF Core:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }
Restart IntelliJ and reimport the Project and import it as maven. It should work then. The error occurs because IntelliJ keeps track of module through .iml files so any changes in these files can cause this error. Reimporting the project regenerates the .iml file so generally, it solves the error.
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
- (NSDate *)earlierDate:(NSDate *)anotherDate
This returns the earlier of the receiver and anotherDate. If both are same, the receiver is returned.
Try using the code after you active the sheet:
Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
If you use Cells.SpecialCells(xlCellTypeLastCell).Row
only, the problem will be that the xlCellTypeLastCell
information will not be updated unless one do a "Save file" action. But use UsedRange
will always update the information in realtime.
Original answer Nov 20 '15:
No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag>
after you call docker-compose.
Now there's an option as described above or here
build: ./dir
image: webapp:tag
Per Ryan Morr's thorough article on this subject...
"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows
function:
public class InfoWindow
{
public IntPtr Handle = IntPtr.Zero;
public FileInfo File = new FileInfo( Application.ExecutablePath );
public string Title = Application.ProductName;
public override string ToString() {
return File.Name + "\t>\t" + Title;
}
}//CLASS
/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{
internal static event EventHandler WindowActivatedChanged;
internal static Timer TimerWatcher = new Timer();
internal static InfoWindow WindowActive = new InfoWindow();
internal static void DoStartWatcher() {
TimerWatcher.Interval = 500;
TimerWatcher.Tick += TimerWatcher_Tick;
TimerWatcher.Start();
}
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
{
IntPtr shellWindow = GetShellWindow();
Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();
EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
if ( hWnd == shellWindow ) return true;
if ( !IsWindowVisible( hWnd ) ) return true;
int length = GetWindowTextLength( hWnd );
if ( length == 0 ) return true;
StringBuilder builder = new StringBuilder( length );
GetWindowText( hWnd , builder , length + 1 );
var info = new InfoWindow();
info.Handle = hWnd;
info.File = new FileInfo( GetProcessPath( hWnd ) );
info.Title = builder.ToString();
windows[hWnd] = info;
return true;
} ) , 0 );
return windows;
}
private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );
public static string GetProcessPath( IntPtr hwnd )
{
uint pid = 0;
GetWindowThreadProcessId( hwnd , out pid );
if ( hwnd != IntPtr.Zero ) {
if ( pid != 0 ) {
var process = Process.GetProcessById( (int) pid );
if ( process != null ) {
return process.MainModule.FileName.ToString();
}
}
}
return "";
}
[DllImport( "USER32.DLL" )]
private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );
[DllImport( "USER32.DLL" )]
private static extern int GetWindowTextLength( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern bool IsWindowVisible( IntPtr hWnd );
[DllImport( "USER32.DLL" )]
private static extern IntPtr GetShellWindow();
[DllImport( "user32.dll" )]
private static extern IntPtr GetForegroundWindow();
//WARN: Only for "Any CPU":
[DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );
static void TimerWatcher_Tick( object sender , EventArgs e )
{
var windowActive = new InfoWindow();
windowActive.Handle = GetForegroundWindow();
string path = GetProcessPath( windowActive.Handle );
if ( string.IsNullOrEmpty( path ) ) return;
windowActive.File = new FileInfo( path );
int length = GetWindowTextLength( windowActive.Handle );
if ( length == 0 ) return;
StringBuilder builder = new StringBuilder( length );
GetWindowText( windowActive.Handle , builder , length + 1 );
windowActive.Title = builder.ToString();
if ( windowActive.ToString() != WindowActive.ToString() ) {
//fire:
WindowActive = windowActive;
if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
Console.WriteLine( "Window: " + WindowActive.ToString() );
}
}
}//CLASS
Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...
Put them in an arrayList in your first class like:
import java.util.ArrayList;
public class numbers {
private int number1 = 50;
private int number2 = 100;
public ArrayList<int> getNumberList() {
ArrayList<int> numbersList= new ArrayList<int>();
numbersList.add(number1);
numberList.add(number2);
....
return numberList;
}
}
Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.
You can also access a variable declared in one class from another simply like
numbers.numberList;
if you have it declared there as public.
But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.
If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.
This is what I used to kill the progress on port 4200
For linux users:
sudo kill $(sudo lsof -t -i:4200)
You could also try this:
sudo kill `sudo lsof -t -i:4200`
For windows users:
Port number 4200 is already in use. Open the cmd as administrator. Type below command in cmd:
netstat -a -n -o
And then, find port with port number 4200 by right click on terminal and click find, enter 4200 in "find what" and click "find next": Let say you found that port number 4200 is used by pid 18932. Type below command in cmd:
taskkill -f /pid 18932
For UNIX:
alias ngf='kill -9 $(lsof -t -i:4200);ng serve'
Now run ngf (instead of ng serve) in terminal from the project folder. This will kill all processes using the port 4200 and runs your Angular project.
That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:
(4 :: List(1,2,3).reverse).reverse
or that:
List(1,2,3) ::: List(4)
use MouseDown, MouseMove and MouseUp. You can set a variable flag for that. I have a sample, but I think you need to revise.
I am coding the mouse action to a panel. Once you click the panel, your form will move with it.
//Global variables;
private bool _dragging = false;
private Point _offset;
private Point _start_point=new Point(0,0);
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true; // _dragging is your variable flag
_start_point = new Point(e.X, e.Y);
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if(_dragging)
{
Point p = PointToScreen(e.Location);
Location = new Point(p.X - this._start_point.X,p.Y - this._start_point.Y);
}
}
Update nginx config /etc/nginx/sites-available/default or your config file
if you are using php7 use this
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
if you are using php5 use this
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
Visit here for complete detail Detail here
Something that works for me. Enjoy.
Excel.Application excelApplication = new Excel.Application() // start excel and turn off msg boxes
{
DisplayAlerts = false,
Visible = false
};
Excel.Workbook workBook = excelApplication.Workbooks.Open(targetFile);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];
var rDT = workSheet.Range(workSheet.Cells[monthYearNameRow, monthYearNameCol], workSheet.Cells[monthYearNameRow, maxTableColumnIndex]);
rDT.Merge();
rDT.Value = monthName + " " + year;
var reportDateRowStyle = workBook.Styles.Add("ReportDateRowStyle");
reportDateRowStyle.HorizontalAlignment = XlHAlign.xlHAlignCenter;
reportDateRowStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
reportDateRowStyle.Font.Bold = true;
reportDateRowStyle.Font.Size = 14;
rDT.Style = reportDateRowStyle;
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
@Semyon Perepelitsa
There is a better solution for this. Blur removes the focus from the input and that is a side affect that you do not want. You should use evt.preventDefault instead. This prevents the default behavior of the input when the user scrolls. Here is the code:
input = document.getElementById("the_number_input")
input.addEventListener("mousewheel", function(evt){ evt.preventDefault(); })
You can use SET ECHO ON
in the beginning of your script to achieve that, however, you have to specify your script using @
instead of <
(also had to add EXIT
at the end):
test.sql
SET ECHO ON
SELECT COUNT(1) FROM dual;
SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);
EXIT
terminal
sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log
test.log
SQL> SQL> SELECT COUNT(1) FROM dual; COUNT(1) ---------- 1 SQL> SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual); COUNT(1) ---------- 2 SQL> SQL> EXIT
The Port is not open. Thats why the machine refuses communication
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
You can do this:
<img src="your image" style="transform:rotate(90deg);">
it is much easier.
This is a simple JavaScript sound recorder and editor. You can try it.
https://www.danieldemmel.me/JSSoundRecorder/
Can download from here
Contrary to some answers posted in this thread, adding 'DIRS': ['templates']
has no effect(it's redundant) since templates
is the default path where Django looks for templates.
If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS
in the main project settings.py
.
INSTALLED_APPS': [
# ...
'my_app',
]
Quoting Django's Templates documentation:
class DjangoTemplates¶
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
When you create an application to your project, there's no templates
directory inside the application directory. Since that you can have an application without using templates, Django doesn't create such directory. That is, you have to create it and storing your templates in there.
Here's another paragraph from Django Tutorial documentation, which is even clearer:
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
Layout changes can occur whenever any of the following events happens in a view:
a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling thesetNeedsLayout
orlayoutIfNeeded
method of a view.
e. Your application forces layout by calling thesetNeedsLayout
method of the view’s underlying layer object.
Try this in your .htaccess:
.htaccess
ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]
RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]
# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]
The ErrorDocument
redirects all 404s to a specific URL, all 500s to another url (replace with your domain).
The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.
Local Redirect:
Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):
ErrorDocument 404 /pages/errors/404_redirect.php
404_redirect.php
<?php
header('Location: /404/');
exit;
?>
Redirect based on error number
Looks like you'll need to specify an ErrorDocument
line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.
error_redirect.php
<?php
$error_url = $_SERVER["REDIRECT_STATUS"] . '/';
$error_path = $error_url . '.php';
if ( ! file_exists($error_path)) {
// this is the default error if a specific error page is not found
$error_url = '404/';
}
header('Location: ' . $error_url);
exit;
?>
I got a simple and permanent solution for this issue in windows.
Go to network and internet option->
click on Etherenet or wifi(for which you are connected) option ->
Click on change adapter option ->
Right click on the network for which you have connected.
A dialog box will be opened and just click on Internet protocal version (TCP/IPv4) option.
Another dialog box will be opened and there just neglect the first set about the IP address (Keep as it is set) and click radio button of Use the following DNS server addresses: and enter as 8.8.8.8 in Preferred DNS server: and 8.8.4.4 in Alternate DNS server:
Now you can open your emulator whenever and you will get internet in the android emulators.
Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.
SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM information_schema.table_privileges
WHERE grantee not in ('pg_monitor','PUBLIC');
MySQL is getting stupid here. It tries to create files under /tmp/data/.... So what you can do is the following:
mkdir /tmp/data
mount --bind /data /tmp/data
Then try your query. This worked for me after hours of debugging the issue.
One way to handle it it to remove something from a copy of a Collection
(not Collection itself), if applicable. Clone
the original collection it to make a copy via a Constructor
.
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
For your specific case, first off, i don't think final
is a way to go considering you intend to modify the list past declaration
private static final List<Integer> integerList;
Also consider modifying a copy instead of the original list.
List<Integer> copy = new ArrayList<Integer>(integerList);
for(Integer integer : integerList) {
if(integer.equals(remove)) {
copy.remove(integer);
}
}
Here simple example to create pandas dataframe by using numpy array.
import numpy as np
import pandas as pd
# create an array
var1 = np.arange(start=1, stop=21, step=1).reshape(-1)
var2 = np.random.rand(20,1).reshape(-1)
print(var1.shape)
print(var2.shape)
dataset = pd.DataFrame()
dataset['col1'] = var1
dataset['col2'] = var2
dataset.head()
For mysql 8.0.19, I finally found the my.cnf here: /usr/local/opt/mysql/.bottle/etc I copied it to /usr/local/opt/mysql/ and modified it. Then I restart the mysql service, it works.
Sample solution. Check, if this is what you need.
<div class="container">
<div class="relative">
<div class="absolute"></div>
<div class="content">
<p>
Content here
</p>
</div>
</div>
</div>
And for CSS
.relative {
position: relative;
}
.absolute {
position: absolute;
top: 15px;
left: 25px;
}
See it on codepen https://codepen.io/FelySpring/pen/jXENXY
<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />
Just put the following below your form. Make sure your input fields are required
.
<script>
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
forms[i].noValidate = true;
forms[i].addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
alert("Please complete all fields and accept the terms.");
}
}, false);
}
</script>
The JDK (Java Development Kit) is an SDK (Software Dev Kit).
It is used to build software/applications on Java and of course it includes the JRE (Java Runtime Edition) to execute that software. If you just want to execute a Java application, download only the JRE.
By the way, Java EE (Enterprise Edition) contains libraries of packages of classes "with methods (functions)" to build apps for the WEB environment and Java ME (Micro Edition) for mobile devices. If you are interested in it (Java ME) I would recommend to take a look at Google's Android DevKit and API.
Take a look here: it's gonna explain bit more.. http://www.oracle.com/technetwork/java/archive-139210.html
Don't hard code image bounds. Just use:
RotateAnimation anim = new RotateAnimation( fromAngle, toAngle, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
These might work. I don't know how they behave when running as a service. They aren't portable, but that's what os.name
and if
statements are for.
win32api.GetUserName()
win32api.GetUserNameEx(...)
See: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.
class CallbackTest {
myCallback: Function;
}
The Problem
I help maintain a big, complicated, messy old site in which everything (literally) is nested in multiple levels of iframes-- many of which are dynamically created and/or have a dynamic src. That creates the following challenges:
Of the solutions posted so far, this is the only one I've seen that overcomes challenge 1. Unfortunately, it doesn't seem to work on some iframes, and when it does, the scrolling is very glitchy (which seems to cause other bugs on the page, such as unresponsive links and form controls).
The Solution
If the above sounds anything like your situation, you may want to give the following script a try. It forgoes native scrolling and instead makes all iframes draggable within the bounds of their viewport. You only need to add it to the document that contains the top level iframes; it will apply the fix as needed to them and their descendants.
Here's a working fiddle*, and here's the code:
(function() {
var mouse = false //Set mouse=true to enable mouse support
, iOS = /iPad|iPhone|iPod/.test(navigator.platform);
if(mouse || iOS) {
(function() {
var currentFrame
, startEvent, moveEvent, endEvent
, screenY, translateY, minY, maxY
, matrixPrefix, matrixSuffix
, matrixRegex = /(.*([\.\d-]+, ?){5,13})([\.\d-]+)(.*)/
, min = Math.min, max = Math.max
, topWin = window;
if(!iOS) {
startEvent = 'mousedown';
moveEvent = 'mousemove';
endEvent = 'mouseup';
}
else {
startEvent = 'touchstart';
moveEvent = 'touchmove';
endEvent = 'touchend';
}
setInterval(scrollFix, 500);
function scrollFix() {fixSubframes(topWin.frames);}
function fixSubframes(wins) {for(var i = wins.length; i; addListeners(wins[--i]));}
function addListeners(win) {
try {
var doc = win.document;
if(!doc.draggableframe) {
win.addEventListener('unload', resetFrame);
doc.draggableframe = true;
doc.addEventListener(startEvent, touchStart);
doc.addEventListener(moveEvent, touchMove);
doc.addEventListener(endEvent, touchEnd);
}
fixSubframes(win.frames);
}
catch(e) {}
}
function resetFrame(e) {
var doc = e.target
, win = doc.defaultView
, iframe = win.frameElement
, style = getComputedStyle(iframe).transform;
if(iframe===currentFrame) currentFrame = null;
win.removeEventListener('unload', resetFrame);
doc.removeEventListener(startEvent, touchStart);
doc.removeEventListener(moveEvent, touchMove);
doc.removeEventListener(endEvent, touchEnd);
if(style !== 'none') {
style = style.replace(matrixRegex, '$1|$3|$4').split('|');
iframe.style.transform = style[0] + 0 + style[2];
}
else iframe.style.transform = null;
iframe.style.WebkitClipPath = null;
iframe.style.clipPath = null;
delete doc.draggableiframe;
}
function touchStart(e) {
var iframe, style, offset, coords
, touch = e.touches ? e.touches[0] : e
, elem = touch.target
, tag = elem.tagName;
currentFrame = null;
if(tag==='TEXTAREA' || tag==='SELECT' || tag==='HTML') return;
for(;elem.parentElement; elem = elem.parentElement) {
if(elem.scrollHeight > elem.clientHeight) {
style = getComputedStyle(elem).overflowY;
if(style==='auto' || style==='scroll') return;
}
}
elem = elem.ownerDocument.body;
iframe = elem.ownerDocument.defaultView.frameElement;
coords = getComputedViewportY(elem.clientHeight < iframe.clientHeight ? elem : iframe);
if(coords.elemTop >= coords.top && coords.elemBottom <= coords.bottom) return;
style = getComputedStyle(iframe).transform;
if(style !== 'none') {
style = style.replace(matrixRegex, '$1|$3|$4').split('|');
matrixPrefix = style[0];
matrixSuffix = style[2];
offset = parseFloat(style[1]);
}
else {
matrixPrefix = 'matrix(1, 0, 0, 1, 0, ';
matrixSuffix = ')';
offset = 0;
}
translateY = offset;
minY = min(0, offset - (coords.elemBottom - coords.bottom));
maxY = max(0, offset + (coords.top - coords.elemTop));
screenY = touch.screenY;
currentFrame = iframe;
}
function touchMove(e) {
var touch, style;
if(currentFrame) {
touch = e.touches ? e.touches[0] : e;
style = min(maxY, max(minY, translateY + (touch.screenY - screenY)));
if(style===translateY) return;
e.preventDefault();
currentFrame.contentWindow.getSelection().removeAllRanges();
translateY = style;
currentFrame.style.transform = matrixPrefix + style + matrixSuffix;
style = 'inset(' + (-style) + 'px 0px ' + style + 'px 0px)';
currentFrame.style.WebkitClipPath = style;
currentFrame.style.clipPath = style;
screenY = touch.screenY;
}
}
function touchEnd() {currentFrame = null;}
function getComputedViewportY(elem) {
var style, offset
, doc = elem.ownerDocument
, bod = doc.body
, elemTop = elem.getBoundingClientRect().top + elem.clientTop
, elemBottom = elem.clientHeight
, viewportTop = elemTop
, viewportBottom = elemBottom + elemTop
, position = getComputedStyle(elem).position;
try {
while(true) {
if(elem === bod || position === 'fixed') {
if(doc.defaultView.frameElement) {
elem = doc.defaultView.frameElement;
position = getComputedStyle(elem).position;
offset = elem.getBoundingClientRect().top + elem.clientTop;
viewportTop += offset;
viewportBottom = min(viewportBottom + offset, elem.clientHeight + offset);
elemTop += offset;
doc = elem.ownerDocument;
bod = doc.body;
continue;
}
else break;
}
else {
if(position === 'absolute') {
elem = elem.offsetParent;
style = getComputedStyle(elem);
position = style.position;
if(position === 'static') continue;
}
else {
elem = elem.parentElement;
style = getComputedStyle(elem);
position = style.position;
}
if(style.overflowY !== 'visible') {
offset = elem.getBoundingClientRect().top + elem.clientTop;
viewportTop = max(viewportTop, offset);
viewportBottom = min(viewportBottom, elem.clientHeight + offset);
}
}
}
}
catch(e) {}
return {
top: max(viewportTop, 0)
,bottom: min(viewportBottom, doc.defaultView.innerHeight)
,elemTop: elemTop
,elemBottom: elemBottom + elemTop
};
}
})();
}
})();
* The jsfiddle has mouse support enabled for testing purposes. On a production site, you'd want to set mouse=false.
Q: What's the difference between __str__()
and __repr__()
?
LONG
This question has been around a long time, and there are a variety of answers of which most are correct (not to mention from several Python community legends[!]). However when it comes down to the nitty-gritty, this question is analogous to asking for the difference between the str()
and repr()
built-in functions. I'm going to describe the differences in my own words (which means I may be "borrowing" liberally from Core Python Programming so pls forgive me).
Both str()
and repr()
have the same basic job: their goal is to return a string representation of a Python object. What kind of string representation is what differentiates them.
str()
& __str()__
return a printable string representation of
an object... something human-readable/for human consumptionrepr()
& __repr()__
return a string representation of an object that is a
valid Python object, something you can pass to eval()
or type into the Python shell without getting an error.For example, let's assign a string to x
and an int
to y
:
>>> x, y = 'foo', 123
>>> str(x), str(y)
('foo', '123')
Can we take what's inside the quotes and enter them verbatim into the Python interpreter?
>>> 123
123
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
Clearly you can for an int
but not necessarily for a str
. While I can pass '123'
to eval()
, that doesn't work for 'foo'
:
>>> eval('123')
123
>>> eval('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
Now let's try repr()
; again, dump what's in the pair of quotes for each string:
>>> repr(x), repr(y)
("'foo'", '123')
>>> 123
123
>>> 'foo'
'foo'
Wow, they both work? That's because 'foo'
, while a printable string representation of that string, it's not evaluatable, but "'foo'"
is. 123
is a valid Python int
called by either str()
or repr()
. What happens when we call eval()
with these?
>>> eval('123')
123
>>> eval("'foo'")
'foo'
It works because 123
and 'foo'
are valid Python objects. Another key takeaway is that while sometimes both return the same thing (the same string representation), that's not always the case. (And yes, yes, I can go create a variable foo
where the eval()
works, but that's not the point.)
More factoids about both pairs
str()
and repr()
are called implicitly, meaning they're called on behalf of users: when users execute print
(Py1/Py2) or call print()
(Py3+), even if users don't call str()
explicitly, such a call is made on their behalf before the object is displayed.>>>
prompt and press RETURN, the interpreter displays the results of repr()
implicitly called on that object.str()
and repr()
to __str__()
and __repr__()
, realize that calls to the built-in functions, i.e., str(x)
or repr(y)
result in calling their object's corresponding special methods: x.__str__()
or y.__repr()__
__str__()
and __repr__()
for your Python classes, you overload the built-in functions (str()
and repr()
), allowing instances of your classes to be passed in to str()
and repr()
. When such calls are made, they turn around and call the class' __str__()
and __repr__()
(per #3).For Eclipse in Macbook it is just 2 click process:
Simply use \1
instead of $1
:
In [1]: import re
In [2]: method = 'images/:id/huge'
In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'
Also note the use of raw strings (r'...'
) for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.
Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:
var fs = require('fs'),
path = require('path');
var dirString = path.dirname(fs.realpathSync(__filename));
// output example: "/Users/jb/workspace/abtest"
console.log('directory to start walking...', dirString);
Building on Amine's answer, create a helper like:
public static class HtmlHelperExtensions
{
public static MvcHtmlString CurrencyFormat(this HtmlHelper helper, string value)
{
var result = string.Format("{0:C2}", value);
return new MvcHtmlString(result);
}
}
in your view: use @Html.CurrencyFormat(model.value)
If you are doing simple formating like Standard Numeric Formats, then simple use string.Format() in your view like in the helper example above:
@string.Format("{0:C2}", model.value)
If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"
Personally, I use Emacs with hexl-mod.
Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.