I created a WSGI middleware that stores the raw body from the environ['wsgi.input']
stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy']
within my app.
This isn't necessary in Werkzeug or Flask, as request.get_data()
will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.
This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length
header is missing, so it won't handle streaming requests.
from io import BytesIO
class WSGICopyBody(object):
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
length = int(environ.get('CONTENT_LENGTH') or 0)
body = environ['wsgi.input'].read(length)
environ['body_copy'] = body
# replace the stream since it was exhausted by read()
environ['wsgi.input'] = BytesIO(body)
return self.application(environ, start_response)
app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']
Elem e = enumerable.FirstOrDefault();
//do something with e
If you have C++11 you can make use of auto
.
for (auto it = my_vector.rbegin(); it != my_vector.rend(); ++it)
{
}
Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Note getSelectedFile()
returns the selected folder, despite the name.
getCurrentDirectory()
returns the directory of the selected folder.
import javax.swing.*;
public class Example
{
public static void main(String[] args)
{
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
}
}
Option 2 is correct.
The nested list should be inside a <li>
element of the list in which it is nested.
Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.
Link to the HTML5 W3C ul
spec: HTML5 ul
. Note that a ul
element may contain exactly zero or more li
elements. The same applies to HTML5 ol
.
The description list (HTML5 dl
) is similar, but allows both dt
and dd
elements.
More Notes:
dl
= definition list.ol
= ordered list (numbers).ul
= unordered list (bullets).You are almost certainly using a different version of the class at runtime to the one you expect. In particular, the runtime class would be different to the one you've compiled against (else this would have caused a compile-time error) - has that method ever been private
? Do you have old versions of the classes/jars on your system anywhere?
As the javadocs for IllegalAccessError
state,
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
I'd definitely look at your classpath and check whether it holds any surprises.
Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque
instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert()
instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:
std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());
You can instead do:
std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_front(nextItem);
}
// No reverse needed - already in correct order
The following code was used in our html5 game.
$(document).ready(function () {
$(window)
.bind('orientationchange', function(){
if (window.orientation % 180 == 0){
$(document.body).css("-webkit-transform-origin", "")
.css("-webkit-transform", "");
}
else {
if ( window.orientation > 0) { //clockwise
$(document.body).css("-webkit-transform-origin", "200px 190px")
.css("-webkit-transform", "rotate(-90deg)");
}
else {
$(document.body).css("-webkit-transform-origin", "280px 190px")
.css("-webkit-transform", "rotate(90deg)");
}
}
})
.trigger('orientationchange');
});
pattern: /[\w\W]{1,10}/g
I used this expression for my case, it includes all the characters available in the text.
For Xcode 4 and higher, open the preferences (command+,) and check "Show: Line numbers" in the "Text Editing" section.
Xcode 8 and below
You can try like this:
SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)
The above code will certainly help in converting HTML to PDF but will fail if the the HTML code has IMG tags with relative paths. iTextSharp library does not automatically convert relative paths to absolute ones.
I tried the above code and added code to take care of IMG tags too.
You can find the code here for your reference: http://www.am22tech.com/html-to-pdf/
a = [[a, 2], [b, 3], [c, 4], [d, 5], [a, 1], [b, 6], [e, 7], [h, 8]]
I need this from above one
a = [[a, 3], [b, 9], [c, 4], [d, 5], [e, 7], [h, 8]]
a.append([0, 0])
for i in range(len(a)):
for j in range(i + 1, len(a) - 1):
if a[i][0] == a[j][0]:
a[i][1] += a[j][1]
del a[j]
a.pop()
You use the modulo operator:
while(score)
{
printf("%d\n", score % 10);
score /= 10;
}
Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.
To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.
for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.
In firefox, this can be done from 'about:preferences' and searching for 'Certificates'
provide all custom services means written by you in component decorator section Example : providers: [serviceName]
note:if you are using service for exchanging data between components. declare providers: [serviceName] in module level
The best solution I found regarding this, and I tried it on 330 MB file.
lineno = 500
line_length = 8
with open('catfour.txt', 'r') as file:
file.seek(lineno * (line_length + 2))
print(file.readline(), end='')
Where line_length is the number of characters in a single line. For example "abcd" has line length 4.
I have added 2 in line length to skip the '\n' character and move to the next character.
To keep the code easy to read, you can use square brackets []
to quote the string containing '
or vice versa .
This seems to be a Babel error. I'm guessing you use babel-loader, and are not excluding external libraries from your loader test. As far as I can tell, the message is not harmful, but you should still do something like this:
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' }
]
Have a look. Was that it?
If it has to be "nested", this would be one way, to get your job done:
SELECT o.name AS country, o.headofstate
FROM country o
WHERE o.headofstate like 'A%'
AND (
SELECT i.population
FROM city i
WHERE i.id = o.capital
) > 100000
A JOIN
would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
As of Hive 0.14, the CSV SerDe is a standard part of the Hive install
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
(See: https://cwiki.apache.org/confluence/display/Hive/CSV+Serde)
Try with this
echo date("G:i", strtotime($time));
or you can try like this also
echo date("H:i", strtotime("04:25 PM"));
Here you can do like this -
val data = df.groupBy("Hour").agg(first("Hour").as("_1"),first("Category").as("Category"),first("TotalValue").as("TotalValue")).drop("Hour")
data.withColumnRenamed("_1","Hour").show
I am using below code for today and database date.
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
According to the documentation, the first argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
With current methods available in Linq it looks quite ugly:
var tasks = items.Select(
async item => new
{
Item = item,
IsValid = await IsValid(item)
});
var tuples = await Task.WhenAll(tasks);
var validItems = tuples
.Where(p => p.IsValid)
.Select(p => p.Item)
.ToList();
Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.
You could use a helper method to get rid of @SuppressWarnings("unchecked")
all over a class.
@SuppressWarnings("unchecked")
private static <T> Class<T> generify(Class<?> cls) {
return (Class<T>)cls;
}
Then you could write
Class<List<Foo>> cls = generify(List.class);
Other usage examples are
Class<Map<String, Integer>> cls;
cls = generify(Map.class);
cls = TheClass.<Map<String, Integer>>generify(Map.class);
funWithTypeParam(generify(Map.class));
public void funWithTypeParam(Class<Map<String, Integer>> cls) {
}
However, since it is rarely really useful, and the usage of the method defeats the compiler's type checking, I would not recommend to implement it in a place where it is publicly accessible.
I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b
The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.
userModel.countDocuments(query).exec((err, count) => {
if (err) {
res.send(err);
return;
}
res.json({ count: count });
});
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
If these two div
elements are basically your main layout elements, and nothing follows them in the html, then there is a pure HMTL/CSS solution that takes the normal order shown in this fiddle and is able to flip it vertically as shown in this fiddle using one additional wrapper div
like so:
HTML
<div class="wrapper flipit">
<div id="first_div">first div</div>
<div id="second_div">second div</div>
</div>
CSS
.flipit {
position: relative;
}
.flipit #first_div {
position: absolute;
top: 100%;
width: 100%;
}
This would not work if elements follow these div's, as this fiddle illustrates the issue if the following elements are not wrapped (they get overlapped by #first_div
), and this fiddle illustrates the issue if the following elements are also wrapped (the #first_div
changes position with both the #second_div
and the following elements). So that is why, depending on your use case, this method may or may not work.
For an overall layout scheme, where all other elements exist inside the two div's, it can work. For other scenarios, it will not.
Imagine it this way: a mail truck can carry 5000 sheets of paper each trip so It's bandwidth is 5000. Does that mean it can carry 5000 letter each trip? Well, theoretically, if each letter didn't need an envelope telling us where it was coming from, going too, and possessing proof of payment (Envelope = Protocol Headers and Footers). But they do, so each letter (1 sheet of paper) requires an envelope (= to about 1 sheet of paper) to get it to it's destination. So in the worst case scenario (all envelopes only have one page letters), the truck would carry only 2500 sheets Throughput (Data that we want to send from source>destination, THE LETTERS) and would have 2500 sheets Overhead (Headers/Footer that we need to get the letter from source>destination but that the recipient won't be reading, THE ENVELOPES). The Throughput, 2500 Letters + the Overhead, 2500 Envelopes = Bandwidth, 5000 sheets of paper. Bigger letters (4 pages) still only require 1 envelope so that would move the ratio of Throughput to Overhead higher (i.e. Jumbo Frames) and make it more efficient, so if all the letters were 4 page letters throughput would change to 4000, and overhead would reduce to 1000, together equaling the 5000 Bandwidth of the truck.
Abolishing the need for an extra element, along with making the content fit within the document flow rather than being fixed/absolute like other solutions.
Achieved using
.content {
/* this is needed or the background will be offset by a few pixels at the top */
overflow: auto;
position: relative;
}
.content::before {
content: "";
position: fixed;
left: 0;
right: 0;
z-index: -1;
display: block;
background-image: url('https://i.imgur.com/lL6tQfy.png');
background-size:cover;
width: 100%;
height: 100%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
EDIT If you are interested in removing the white borders at the edges, use a width and height of 110%
and a left and top of -5%
. This will enlarge your backgrounds a tad - but there should be no solid colour bleeding in from the edges. Thanks Chad Fawcett for the suggestion.
.content {
/* this is needed or the background will be offset by a few pixels at the top */
overflow: auto;
position: relative;
}
.content::before {
content: "";
position: fixed;
top: -5%;
left: -5%;
right: -5%;
z-index: -1;
display: block;
background-image: url('https://i.imgur.com/lL6tQfy.png');
background-size:cover;
width: 110%;
height: 110%;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
The native JavaScript implementation is Date.now()
.
Date.now()
and $.now()
return the same value:
Date.now(); // 1421715573651
$.now(); // 1421715573651
new Date(Date.now()) // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
new Date($.now()); // Mon Jan 19 2015 20:02:55 GMT-0500 (Eastern Standard Time)
..and if you want the time formatted in hh-mm-ss:
var now = new Date(Date.now());
var formatted = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
// 20:10:58
It looks like you want to use a list instead:
group=[]
for i in range(3):
group[i]=self.getGroup(selected, header+i)
You can simply use the return;
example
$(document).ready(function () {
alert(1);
return;
alert(2);
alert(3);
alert(4);
});
The return will return to the main caller function test1(); and continue from there to test3();
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
return;
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
but if you just add throw ''; this will completely stop the execution without causing any errors.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/javascript">
function test1(){
test2();
test3();
}
function test2(){
alert(2);
throw '';
test4();
test5();
}
function test3(){
alert(3);
}
function test4(){
alert(4);
}
function test5(){
alert(5);
}
test1();
</script>
</body>
</html>
This is tested with firefox and chrome. I don't know how this is handled by IE or Safari
This is a simple blocking technique:
var waitTill = new Date(new Date().getTime() + seconds * 1000);
while(waitTill > new Date()){}
It's blocking insofar as nothing else will happen in your script (like callbacks). But since this is a console script, maybe it is what you need!
isset()
will return true if the variable has been initialised. If you have a form field with its name
value set to userName
, when that form is submitted the value will always be "set", although there may not be any data in it.
Instead, trim()
the string and test its length
if("" == trim($_POST['userName'])){
$username = 'Anonymous';
}
In one line, answer is as below;
[ CASE WHEN COLUMN_NAME = 'VALUE' THEN 'SHOW_THIS' ELSE 'SHOW_OTHER' END as ALIAS ]
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
A simpler and lighter version that doesn't use reflection:
abstract class enum {
private function __construct() {}
static function has($const) {
$name = get_called_class();
return defined("$name::$const");
}
static function value($const) {
$name = get_called_class();
return defined("$name::$const")? constant("$name::$const") : false;
}
}
Usage:
class requestFormat extends enum { const HTML = 1; const JSON = 2; const XML = 3; const FORM = 4; }
echo requestFormat::value('JSON'); // 2
echo requestFormat::has('JSON'); // true
This gives the advantage of constants and also allows for checking the validity of them but it lacks other fancy functionality provided by more complex solutions given is this question, the more obvious the inability of checking the reverse of a value (in the example above, you can't check if '2' is a valid value)
Given the sample you posted, this simple code should do the job:
fid = fopen('file.csv','r');
C = textscan(fid, repmat('%s',1,10), 'delimiter',';', 'CollectOutput',true);
C = C{1};
fclose(fid);
Then you could format the columns according to their type. For example if the first column is all integers, we can format it as such:
C(:,1) = num2cell( str2double(C(:,1)) )
Similarly, if you wish to convert the 8th column from hex to decimals, you can use HEX2DEC:
C(:,8) = cellfun(@hex2dec, strrep(C(:,8),'0x',''), 'UniformOutput',false);
The resulting cell array looks as follows:
C =
[ 4] 'abc' 'def' 'ghj' 'klm' '' '' [] '' ''
[NaN] '' '' '' '' 'Test' 'text' [ 255] '' ''
[NaN] '' '' '' '' 'asdfhsdf' 'dsafdsag' [3855] '' ''
Here a full makefile example:
makefile
TARGET = prog
$(TARGET): main.o lib.a
gcc $^ -o $@
main.o: main.c
gcc -c $< -o $@
lib.a: lib1.o lib2.o
ar rcs $@ $^
lib1.o: lib1.c lib1.h
gcc -c -o $@ $<
lib2.o: lib2.c lib2.h
gcc -c -o $@ $<
clean:
rm -f *.o *.a $(TARGET)
explaining the makefile:
target: prerequisites
- the rule head$@
- means the target$^
- means all prerequisites$<
- means just the first prerequisitear
- a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
r
- replace files existing inside the archivec
- create a archive if not already existents
- create an object-file index into the archiveTo conclude: The static library under Linux is nothing more than a archive of object files.
main.c using the lib
#include <stdio.h>
#include "lib.h"
int main ( void )
{
fun1(10);
fun2(10);
return 0;
}
lib.h the libs main header
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED
#include "lib1.h"
#include "lib2.h"
#endif
lib1.c first lib source
#include "lib1.h"
#include <stdio.h>
void fun1 ( int x )
{
printf("%i\n",x);
}
lib1.h the corresponding header
#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun1 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB1_H_INCLUDED */
lib2.c second lib source
#include "lib2.h"
#include <stdio.h>
void fun2 ( int x )
{
printf("%i\n",2*x);
}
lib2.h the corresponding header
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun2 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB2_H_INCLUDED */
http://neo4j.org/ is a graph database that contains many of graph algorithms and scales better than most in-memory libraries.
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Yes, it is possible. Here is the solution
export interface Foo {
test(): void;
}
export namespace Foo {
export function statMethod(): void {
console.log(2);
}
}
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
This is how i renamed package for both ios and android
applicationId "com.company.name"
app/src/main
and rename package="com.company.name"
and android:label="App Name"
app/src/debug
and rename package="com.company.name"
app/src/profile
and rename package="com.company.name"
app/src/main/kotlin/com/something/something/MainActivity.kt
and rename package="com.company.name"
app/src/main/kotlin/
and rename each directory so that the structure looks like app/src/main/kotlin/com/company/name/
pubspec.yaml
in your project and change name: something
to name: name
, example :- if package name is com.abc.xyz
the name: xyz
com.company.name
flutter clean
I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).
Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.
These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".
So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.
So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.
Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.
Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.
I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.
You can try like this:
var x= str== null
? string.Empty
: str.Substring(0, Math.Min(5, str.Length));
If you don't want to save method into jQuery.fn you can use
[].reverse.call($('li'));
I had a lot of trouble getting the stickytableheaders library to work. Doing a bit more searching, I found floatThead is an actively maintained alternative with recent updates and better documentation.
For me, I tried manage app execution aliases
and got an error that python3 is not a command so for that, I used py
instead of python3
and it worked
I don't know why this is happening but It worked for me
I would just create a separate CSS class:
.ButtonClicked {
background-color:red;
}
And then add the class on click:
$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});
This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ?
and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.
You can also create the ability to have an "on/off" switch feel by toggling the class:
$('#ButtonId').on('click',function(){
$(this).toggleClass('ButtonClicked');
});
Shown by this jsFiddle. Just food for thought.
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?
You can use this working script:
/**
* @param {range} countRange Range to be evaluated
* @param {range} colorRef Cell with background color to be searched for in countRange
* @return {number}
* @customfunction
*/
function countColoredCells(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var rangeA1Notation = formula.match(/\((.*)\,/).pop();
var range = activeSheet.getRange(rangeA1Notation);
var bg = range.getBackgrounds();
var values = range.getValues();
var colorCellA1Notation = formula.match(/\,(.*)\)/).pop();
var colorCell = activeSheet.getRange(colorCellA1Notation);
var color = colorCell.getBackground();
var count = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] == color )
count=count+1;
return count;
};
Then call this function in your google sheets:
=countColoredCells(D5:D123,Z11)
This code is ill-formed:
int&const icr=i;
Reference: C++17 [dcl.ref]/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.
This rule has been present in all standardized versions of C++. Because the code is ill-formed:
The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.
NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?
Add the following as a additional linker option:
/ignore:4099
This is in Properties->Linker->Command Line
you can't force refresh but you can forward all old ip requests to new one. for a website:
replace [OLD_IP] with old server's ip
replace [NEW_IP] with new server's ip
run & win.
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
In situations like this, why not write your own? A simple server app to test connections can be done in a matter of minutes if you know what you're doing, and you can make it respond exactly how you need to, and for specific scenarios.
Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.
This is the way methods like ArrayList.toArray(T[])
are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.
Another thing you could try is to upload the html to a webpage and then open the webpage in word to test Outlook.
I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.
To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell
First step is to check sessionStorage
for some pre-defined value and if it exists alert user:
if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');
Second step is to set sessionStorage
to some value (for example true
):
sessionStorage.setItem("is_reloaded", true);
Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
hey first of all to include c++ functions you should use
include
<iostream.h>
instead of stdio .hand to hold the output screen there is a simple command getch(); here, is an example:
#include<iostream.h>
#include<conio.h>
void main() \\or int main(); if you want
{
cout<<"c# is more advanced than c++";
getch();
}
thank you
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.
>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}
On a side note, in PowerShell 3.0 you can use the Get-Content
cmdlet with the new Raw switch:
$text = Get-Content .\file.txt -Raw
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode
has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode
to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray
to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).
Here is a full program example of a for-each macro in C99:
#include <stdio.h>
typedef struct list_node list_node;
struct list_node {
list_node *next;
void *data;
};
#define FOR_EACH(item, list) \
for (list_node *(item) = (list); (item); (item) = (item)->next)
int
main(int argc, char *argv[])
{
list_node list[] = {
{ .next = &list[1], .data = "test 1" },
{ .next = &list[2], .data = "test 2" },
{ .next = NULL, .data = "test 3" }
};
FOR_EACH(item, list)
puts((char *) item->data);
return 0;
}
Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --
I don't like setting position using css()
, though often it's fine. I think the best bet is to use jQuery UI's position()
setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:
const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
left: baseOffset.left + leftOffset,
top: baseOffset.top + topOffset
});
This has the advantage of not arbitrarily setting $div
's parent to relative positioning (what if $div
's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div
doesn't have any offsetParent
, not sure if it would return document
, null
, or something else entirely.
offsetParent
has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.
I just solve this by encode params in the url.
URL may be: http://abc/dgdc.php?p1=Hello&p2=some words
we just need to encode the params2.
$params2 = "some words";
$params2 = urlencode($params2);
$url = "http://abc/dgdc.php?p1=djkl&p2=$params2"
$result = file_get_contents($url);
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key
prop in root element which is looped over in JSX tree of .map()
. Also adding React's Fragment
will avoid adding another element in between of ul
and li
when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key
prop also matters as common way is to use index
parameter provided by .map()
.
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id
from data which is being iterated such as item.id
. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
To add new directory:
mkdir <YOUR-DIRECTORY>
But now Git is not aware by this new directory, because Git keep tracks of file not directories DIRECTORY
git status
Git won't be aware with the change we've made, so we add hidden .keep
file to make Git aware by this new change.
touch /YOUR-directory/.keep
Now, if you hit git status
Git will be aware with the changes.
And If you want to delete the directory, you should use this command.
rm -r <YOUR-DIRECTORY>
And If you checked by using git status
, you will see the directory has been removed.
I created a project to easily initiate a project skeleton from scratch. https://github.com/MacHu-GWU/pygitrepo-project.
And you can create a test project, let's say, learn_creating_py_package
.
You can learn what component you should have for different purpose like:
The advantage of using pygitrepo
is that those tedious are automatically created itself and adapt your package_name
, project_name
, github_account
, document host service
, windows or macos or linux
.
It is a good place to learn develop a python project like a pro.
Hope this could help.
Thank you.
Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.
You need to do something like this:
externalNativeBuild{
ndkBuild{
path "Android.mk"
}
}
defaultConfig {
externalNativeBuild{
ndkBuild {
arguments "NDK_APPLICATION_MK:=Application.mk"
cFlags "-DTEST_C_FLAG1" "-DTEST_C_FLAG2"
cppFlags "-DTEST_CPP_FLAG2" "-DTEST_CPP_FLAG2"
abiFilters "armeabi-v7a", "armeabi"
}
}
}
See http://tools.android.com/tech-docs/external-c-builds
NB: The extra nesting of externalNativeBuild
inside defaultConfig
was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.
If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.
Using CliWrap:
var result = await Cli.Wrap("foobar.bat").ExecuteBufferedAsync();
var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;
Yes it should be fixed, HAXM isn't working.
HAXM sometimes works; experience with HAXM is currently sporadic across platforms.
For instance, I've got late 2009 iMac running 10.8.5 and i7 processor @2.8Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration on this iMac machine, API19 chokes out.
I also have early 2013 MBP 15" Retina running 10.8.5 and i7 processor @2.7Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration, API19 works great too.
Ditto for my (personal) late 2013 MBP Retina 13" with dual-core i5 and Mavericks.
There is something going on for virtualization at the chip level missing from older CPU's (even i7's) that the new API19 x86 images need for HAXM to work. If API19 is not working, give API17 or even 16 a try.
Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.
However, to answer your question, this function should convert any array into a 1-based version
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
Here's a more reusable/flexible function, should you desire it
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
print_r( reIndexArray( $arr ) );
print_r( reIndexArray( $arr, 1 ) );
print_r( reIndexArray( $arr, 2 ) );
print_r( reIndexArray( $arr, 10 ) );
print_r( reIndexArray( $arr, -10 ) );
echo '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
Arrays:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
If you have arrays of objects... you can iterate through the children:
{{#each array}}
//each this = { key: value, key: value, ...}
{{#each this}}
//each key=@key and value=this of child object
{{@key}}: {{this}}
//Or get index number of parent array looping
{{@../index}}
{{/each}}
{{/each}}
Objects:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
If you have nested objects you can access the key
of parent object with
{{@../key}}
use float: left;
and clear: left;
.text span {
background: rgba(165, 220, 79, 0.8);
float: left;
clear: left;
padding: 7px 10px;
color: #fff;
}
function isDeviceMobile(){
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
return isMobile.any()
}
In Python 3, the behaviour changes.
>>> import my_stuff
... do something with my_stuff, then later:
>>>> import imp
>>>> imp.reload(my_stuff)
and you get a brand new, reloaded my_stuff.
We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:
Set up the security context like so:
<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
<security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
<security:intercept-url pattern="/authenticate" access="permitAll"/>
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
<bean id="CustomAuthenticationEntryPoint"
class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />
<bean id="authenticationTokenProcessingFilter"
class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
<constructor-arg ref="authenticationManager" />
</bean>
As you can see, we've created a custom AuthenticationEntryPoint
, which basically just returns a 401 Unauthorized
if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter
.
CustomAuthenticationEntryPoint:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
}
}
AuthenticationTokenProcessingFilter:
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
@Autowired UserService userService;
@Autowired TokenUtils tokenUtils;
AuthenticationManager authManager;
public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
this.authManager = authManager;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
@SuppressWarnings("unchecked")
Map<String, String[]> parms = request.getParameterMap();
if(parms.containsKey("token")) {
String token = parms.get("token")[0]; // grab the first "token" parameter
// validate the token
if (tokenUtils.validate(token)) {
// determine the user based on the (already validated) token
UserDetails userDetails = tokenUtils.getUserFromToken(token);
// build an Authentication object with the user's info
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
// set the authentication into the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));
}
}
// continue thru the filter chain
chain.doFilter(request, response);
}
}
Obviously, TokenUtils
contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:
public interface TokenUtils {
String getToken(UserDetails userDetails);
String getToken(UserDetails userDetails, Long expiration);
boolean validate(String token);
UserDetails getUserFromToken(String token);
}
That ought to get you off to a good start. Happy coding. :)
That is a very strange way to organize things. If you stored in a dictionary, this is easy:
# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
if not url in urls_d:
urls_d[url] = 1
else:
urls_d[url] += 1
This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict
, created just to make this even easier:
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
If you access the defaultdict
using a key, and the key is not already in the defaultdict
, the key is automatically added with a default value. The defaultdict
takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int
; when Python calls int()
it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.
But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter
You just create a Counter
instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:
from collections import Counter # available in Python 2.7 and newer
urls_d = Counter(list_of_urls)
If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]
If you are using Python 2.7 or newer you can do it in a one-liner:
from collections import Counter
urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]
There is no need to make a list. The following works for even-length strings:
r = ''
for in in range(0, len(s), 2) :
r += s[i + 1] + s[i]
s = r
Quickest and easiest way is to use the 'at' command:
ssh user@target "at now -f /home/foo.sh"
You can also manually tag the column with a contrasts
attribute, which seems to be respected by the regression functions:
contrasts(df$factorcol) <- contr.treatment(levels(df$factorcol),
base=which(levels(df$factorcol) == 'RefLevel'))
This had me in Xcode 9 for half a frustrating day. It ended up been a simple debug setting.
Go Debug > Debug Workflow and make sure 'Always Show Disassembly' is turned off. Simple as that. :(
I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):
import sys
import os
sys.path.append(os.getcwd() + '/your/subfolder/of/choice')
# now import whatever other modules you want, both the standard ones,
# as the ones supplied in your subfolders
This will append the relative path of your subfolder to the directories for python to look in It's pretty quick and dirty, but it works like a charm :)
No scroll (without specifying x or y):
.your-class {
overflow: hidden;
}
Remove horizontal scroll:
.your-class {
overflow-x: hidden;
}
Remove vertical scroll:
.your-class {
overflow-y: hidden;
}
If you want to run docker as non-root user then you need to add it to the docker group.
$ sudo groupadd docker
$ sudo usermod -aG docker $USER
$ newgrp docker
$ docker run hello-world
Reboot if still got error
$ reboot
Taken from the docker official documentation: manage-docker-as-a-non-root-user
Just call these two functions
finish();
moveTaskToBack(true);
Do it in 2 steps. First, create a dictionary.
>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for v, k in input: res[k].append(v)
...
Then, convert that dictionary into the expected format.
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]
It is also possible with itertools.groupby but it requires the input to be sorted first.
>>> sorted_input = sorted(input, key=itemgetter(1))
>>> groups = groupby(sorted_input, key=itemgetter(1))
>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups]
[{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]
Note both of these do not respect the original order of the keys. You need an OrderedDict if you need to keep the order.
>>> from collections import OrderedDict
>>> res = OrderedDict()
>>> for v, k in input:
... if k in res: res[k].append(v)
... else: res[k] = [v]
...
>>> [{'type':k, 'items':v} for k,v in res.items()]
[{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]
Install the gd library also.
check this link http://www.php.net/manual/en/mbstring.installation.php
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
myString.toInt()
- convert the string value into int .
Swift 3.x
If you have an integer hiding inside a string, you can convertby using the integer's constructor, like this:
let myInt = Int(textField.text)
As with other data types (Float and Double) you can also convert by using NSString:
let myString = "556"
let myInt = (myString as NSString).integerValue
To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}
:
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"
# prints 'I love Sara and Marry'
To replace all occurrences, use ${parameter//pattern/string}
:
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)
Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
A small and short way of doing the same
HTML
<div class="image">
<p>
<h3>Heading 3</h3>
<h5>Heading 5</h5>
</p>
</div>
CSS
.image {
position: relative;
margin-bottom: 20px;
width: 100%;
height: 300px;
color: white;
background: url('../../Images/myImg.jpg') no-repeat;
background-size: 250px 250px;
}
I prefer to create queries with SQLAlchemy, and then make a DataFrame from it. SQLAlchemy makes it easier to combine SQL conditions Pythonically if you intend to mix and match things over and over.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pandas import DataFrame
import datetime
# We are connecting to an existing service
engine = create_engine('dialect://user:pwd@host:port/db', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
# And we want to query an existing table
tablename = Table('tablename',
Base.metadata,
autoload=True,
autoload_with=engine,
schema='ownername')
# These are the "Where" parameters, but I could as easily
# create joins and limit results
us = tablename.c.country_code.in_(['US','MX'])
dc = tablename.c.locn_name.like('%DC%')
dt = tablename.c.arr_date >= datetime.date.today() # Give me convenience or...
q = session.query(tablename).\
filter(us & dc & dt) # That's where the magic happens!!!
def querydb(query):
"""
Function to execute query and return DataFrame.
"""
df = DataFrame(query.all());
df.columns = [x['name'] for x in query.column_descriptions]
return df
querydb(q)
Try this. It works with me. Hope you too!
List<YOUR_OBJECT> testList = new ArrayList<>();_x000D_
testList.add(test1);_x000D_
_x000D_
Gson gson = new Gson();_x000D_
_x000D_
String json = gson.toJson(testList);_x000D_
_x000D_
Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();_x000D_
_x000D_
ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
_x000D_
(0...8).map { (65 + rand(26)).chr }.join
I spend too much time golfing.
(0...50).map { ('a'..'z').to_a[rand(26)] }.join
And a last one that's even more confusing, but more flexible and wastes fewer cycles:
o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join
Jan 2020 Update
@Flimm has explained all the differences very well. Generally, we want to know the difference between all tools because we want to decide what's best for us. So, the next question would be: which one to use? I suggest you choose one of the two official ways to manage virtual environments:
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
Another solution for this issue is use commons-lang (since version 2.0) StringUtils.substringBetween(String str, String open, String close)
method. Main advantage is that it's null safe operation.
StringUtils.substringBetween("[wdsd34svdf]", "[", "]"); // returns wdsd34svdf
It got this error because I had managed to clobber jdk1.8.0_60 with the jre!
Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).
If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.
Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.
If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)
), you can use do it in linear time using min
:
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
That looks gnarly at first, but looking at your previous questions, you have a List<String>
. In short: min
works on it.
For the long answer: all that super
and extends
stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)
Producer Extends, Consumer Super
It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)
The accepted answer has to load the whole file into memory, which doesn't work nicely for large files. The following solution writes the file contents with the new data inserted into the right line to a temporary file in the same directory (so on the same file system), only reading small chunks from the source file at a time. It then overwrites the source file with the contents of the temporary file in an efficient way (Python 3.8+).
from pathlib import Path
from shutil import copyfile
from tempfile import NamedTemporaryFile
sourcefile = Path("/path/to/source").resolve()
insert_lineno = 152 # The line to insert the new data into.
insert_data = "..." # Some string to insert.
with sourcefile.open(mode="r") as source:
destination = NamedTemporaryFile(mode="w", dir=str(sourcefile.parent))
lineno = 1
while lineno < insert_lineno:
destination.file.write(source.readline())
lineno += 1
# Insert the new data.
destination.file.write(insert_data)
# Write the rest in chunks.
while True:
data = source.read(1024)
if not data:
break
destination.file.write(data)
# Finish writing data.
destination.flush()
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile(destination.name, str(sourcefile))
# Delete the temporary file.
destination.close()
EDIT 2020-09-08: I just found an answer on Code Review that does something similar to above with more explanation - it might be useful to some.
IF YOU HAVE A STRING WITH HTML CODE INSIDE YOU CAN USE:
extension String {
var utfData: Data? {
return self.data(using: .utf8)
}
var htmlAttributedString: NSAttributedString? {
guard let data = self.utfData else {
return nil
}
do {
return try NSAttributedString(data: data,
options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
} catch {
print(error.localizedDescription)
return nil
}
}
var htmlString: String {
return htmlAttributedString?.string ?? self
}
}
AND IN YOUR CODE YOU USE:
label.text = "something".htmlString
Just as we refer to scrolling
class
$( ".scrolling" ).each( function(){
var img = $( "img", this );
$(this).width( img.width() * img.length * 1.2 )
})
Simplest Answer -----------------------------------------
[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults !visiblepw
Defaults always_set_home
Defaults match_group_by_gid
Defaults always_query_group_plugin
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root ALL=(ALL) ALL
%wheel ALL=(ALL) ALL
[root@node1 ~]#
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
Here is my response to the problem described in the question.
in cmd write:
php artisan cache:clear
then try to do this code in your terminal
php artisan serve
note: this will start again the server
Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H
instead of h
in the format string.
E.g
HH:mm:ss
instead of
hh:mm:ss
To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.
#function call
read_names(names.txt)
#function def
def read_names(filename):
with open(filename, 'r') as fileopen:
name_list = [line.strip() for line in fileopen]
print (name_list)
You need to define static variables in a translation unit, unless they are of integral types.
In your header:
private:
static const char *SOMETHING;
static const int MyInt = 8; // would be ok
In the .cpp file:
const char *YourClass::SOMETHING = "something";
C++ standard, 9.4.2/4:
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
One more reason why read the documentation for Symfony will never go out of trend. There is a simple solution for my specific case and is to set the field type
option empty_data
to a default value.
Again, this solution is only for the scenario where an empty input in a form sets the DB field to null.
None of the previous answers helped me with my specific scenario but I found a solution.
I had a form field that needed to behave as follow:
I then tried all the recommendations given in here. Let me list them:
<?php
/**
* @Entity
*/
class myEntity {
/**
* @var string
*
* @Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
@ORM\Column(name="foo", options={"default":"foo bar"})
/**
* @Entity
*/
class myEntity {
...
public function __construct()
{
$this->myColumn = 'myDefaultValue';
}
...
}
None of it worked and all because of how Symfony uses your Entity class.
Symfony form fields override default values set on the Entity class.
Meaning, your schema for your DB can have a default value defined but if you leave a non-required field empty when submitting your form, the form->handleRequest()
inside your form->isValid()
method will override those default values on your Entity
class and set them to the input field values. If the input field values are blank, then it will set the Entity
property to null
.
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
Set the default value on your controller after form->handleRequest()
inside your form->isValid()
method:
...
if ($myEntity->getMyColumn() === null) {
$myEntity->setMyColumn('myDefaultValue');
}
...
Not a beautiful solution but it works. I could probably make a validation group
but there may be people that see this issue as a data transformation rather than data validation, I leave it to you to decide.
I also tried to override the Entity
setter this way:
...
/**
* Set myColumn
*
* @param string $myColumn
*
* @return myEntity
*/
public function setMyColumn($myColumn)
{
$this->myColumn = ($myColumn === null || $myColumn === '') ? 'myDefaultValue' : $myColumn;
return $this;
}
...
This, even though it looks cleaner, it doesn't work. The reason being that the evil form->handleRequest()
method does not use the Model's setter methods to update the data (dig into form->setData()
for more details).
Swift 3
class MyObject: NSObject, NSCoding {
let name : String
let url : String
let desc : String
init(tuple : (String,String,String)){
self.name = tuple.0
self.url = tuple.1
self.desc = tuple.2
}
func getName() -> String {
return name
}
func getURL() -> String{
return url
}
func getDescription() -> String {
return desc
}
func getTuple() -> (String, String, String) {
return (self.name,self.url,self.desc)
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.url, forKey: "url")
aCoder.encode(self.desc, forKey: "desc")
}
}
to store and retrieve:
func save() {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
UserDefaults.standard.set(data, forKey:"customData" )
}
func get() -> MyObject? {
guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
}
Be warned, the majority of the mathematically calculated examples have a hard limit of 2038-01-18
dates and will not work with fictional dates.
As there was a lack of DateTime
and DateInterval
based examples, I wanted to provide a multi-purpose function that satisfies the OP's need and others wanting compound elapsed periods, such as 1 month 2 days ago
. Along with a bunch of other use cases, such as a limit to display the date instead of the elapsed time, or to filter out portions of the elapsed time result.
Additionally the majority of the examples assume elapsed is from the current time, where the below function allows for it to be overridden with the desired end date.
/**
* multi-purpose function to calculate the time elapsed between $start and optional $end
* @param string|null $start the date string to start calculation
* @param string|null $end the date string to end calculation
* @param string $suffix the suffix string to include in the calculated string
* @param string $format the format of the resulting date if limit is reached or no periods were found
* @param string $separator the separator between periods to use when filter is not true
* @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
* @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
* @param int $minimum the minimum value needed to include a period
* @return string
*/
function elapsedTimeString($start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1)
{
$dates = (object) array(
'start' => new DateTime($start ? : 'now'),
'end' => new DateTime($end ? : 'now'),
'intervals' => array('y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'),
'periods' => array()
);
$elapsed = (object) array(
'interval' => $dates->start->diff($dates->end),
'unknown' => 'unknown'
);
if ($elapsed->interval->invert === 1) {
return trim('0 seconds ' . $suffix);
}
if (false === empty($limit)) {
$dates->limit = new DateTime($limit);
if (date_create()->add($elapsed->interval) > $dates->limit) {
return $dates->start->format($format) ? : $elapsed->unknown;
}
}
if (true === is_array($filter)) {
$dates->intervals = array_intersect($dates->intervals, $filter);
$filter = false;
}
foreach ($dates->intervals as $period => $name) {
$value = $elapsed->interval->$period;
if ($value >= $minimum) {
$dates->periods[] = vsprintf('%1$s %2$s%3$s', array($value, $name, ($value !== 1 ? 's' : '')));
if (true === $filter) {
break;
}
}
}
if (false === empty($dates->periods)) {
return trim(vsprintf('%1$s %2$s', array(implode($separator, $dates->periods), $suffix)));
}
return $dates->start->format($format) ? : $elapsed->unknown;
}
One thing to note - the retrieved intervals for the supplied filter values do not carry over to the next period. The filter merely displays the resulting value of the supplied periods and does not recalculate the periods to display only the desired filter total.
Usage
For the OP's need of displaying the highest period (as of 2015-02-24).
echo elapsedTimeString('2010-04-26');
/** 4 years ago */
To display compound periods and supply a custom end date (note the lack of time supplied and fictional dates).
echo elapsedTimeString('1920-01-01', '2500-02-24', null, false);
/** 580 years 1 month 23 days ago */
To display the result of filtered periods (ordering of array doesn't matter).
echo elapsedTimeString('2010-05-26', '2012-02-24', null, ['month', 'year']);
/** 1 year 8 months ago */
To display the start date in the supplied format (default Y-m-d) if the limit is reached.
echo elapsedTimeString('2010-05-26', '2012-02-24', '1 year');
/** 2010-05-26 */
There are bunch of other use cases. It can also easily be adapted to accept unix timestamps and/or DateInterval objects for the start, end, or limit arguments.
If you dont need the whole Type variable and just want to check the type you can easily create a temp variable and use is operator.
T checkType = default(T);
if (checkType is MyClass)
{}
Thanks a bundle, guys. You are great.
I used Chuff's answer and modified it a little to do what I wanted.
I have 2 worksheets in the same workbook.
On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message
Then I inserted a new blank column next to the phone number
On worksheet 2 I have two columns: phone number, name of person
Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.
Then just copy the formula down the whole column until last sms It worked beautifully.
=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)
Here is a way to do it without adding an ID to the form elements.
<form method="post">
...
<select name="List">
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
<select name="List">
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
...
</form>
public ActionResult OrderProcessor()
{
string[] ids = Request.Form.GetValues("List");
}
Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:
public class OrderModel
{
public string[] List { get; set; }
}
public ActionResult OrderProcessor(OrderModel model)
{
string[] ids = model.List;
}
Hope this helps.
What is the difference between == and === and why would you want to use == at all?
Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform
one class to another with preassumption of the developer knows and understand the similarity of 2 classes.
There's no existing solution for transforming between objects. What you can try out are:
Sharing a simple and working solution for posterity. When we run a docker container without explicitly mentioning the --network
flag, it connects to its default bridge network which prohibits connecting to the outside world. To resolve this issue, we have to create our own bridge network(user-defined bridge) and have to explicitly mention it with the docker run command.
docker network create --driver bridge mynetwork
docker run -it --network mynetwork image:version
If you don't care about the number of occurrences, I would approach it like this. Using hash sets will give you better performance than simple iteration.
var set1 = new HashSet<MyType>(list1);
var set2 = new HashSet<MyType>(list2);
return set1.SetEquals(set2);
This will require that you have overridden .GetHashCode()
and implemented IEquatable<MyType>
on MyType
.
You can do this with far less code:
function callPlayer(func, args) {
var i = 0,
iframes = document.getElementsByTagName('iframe'),
src = '';
for (i = 0; i < iframes.length; i += 1) {
src = iframes[i].getAttribute('src');
if (src && src.indexOf('youtube.com/embed') !== -1) {
iframes[i].contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
}), '*');
}
}
}
Working example: http://jsfiddle.net/kmturley/g6P5H/296/
i++ is known as Post Increment whereas ++i is called Pre Increment.
i++
i++
is post increment because it increments i
's value by 1 after the operation is over.
Lets see the following example:
int i = 1, j;
j = i++;
Here value of j = 1
but i = 2
. Here value of i
will be assigned to j
first then i
will be incremented.
++i
++i
is pre increment because it increments i
's value by 1 before the operation.
It means j = i;
will execute after i++
.
Lets see the following example:
int i = 1, j;
j = ++i;
Here value of j = 2
but i = 2
. Here value of i
will be assigned to j
after the i
incremention of i
.
Similarly ++i
will be executed before j=i;
.
For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one.. doesn't matter. It will execute your for loop same no. of times.
for(i=0; i<5; i++)
printf("%d ",i);
And
for(i=0; i<5; ++i)
printf("%d ",i);
Both the loops will produce same output. ie 0 1 2 3 4
.
It only matters where you are using it.
for(i = 0; i<5;)
printf("%d ",++i);
In this case output will be 1 2 3 4 5
.
Make sure to have a header with 'content-type': 'multipart/form-data'
_handleSubmit(e) {
e.preventDefault();
const formData = new FormData();
formData.append('file', this.state.file);
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
axios.post("/upload", formData, config)
.then((resp) => {
console.log(resp)
}).catch((error) => {
})
}
_handleImageChange(e) {
e.preventDefault();
let file = e.target.files[0];
this.setState({
file: file
});
}
#html
<input className="form-control"
type="file"
onChange={(e)=>this._handleImageChange(e)}
/>
As of 2017, WebKit announces support for WebRTC on Safari
Now you can access them with video
and standard javascript WebRTC
E.g.
var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';
/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
audio: false,
video: {
facingMode: facingMode
}
};
/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
video.srcObject = stream;
});
Have a play with it.
Add:
function my_url(){
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
echo $url;
}
Then just call the my_url
function.
Better example is here
try {
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (Field1 VARCHAR, Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Field1, Field2)"
+ " VALUES ('Saranga', 22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
int Column1 = c.getColumnIndex("Field1");
int Column2 = c.getColumnIndex("Field2");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
I created an Interface and a <options>
tag helper for this. So I didn't have to convert the IEnumerable<T>
items into IEnumerable<SelectListItem>
every time I have to populate the <select>
control.
And I think it works beautifully...
The usage is something like:
<select asp-for="EmployeeId">
<option value="">Please select...</option>
<options asp-items="@Model.EmployeesList" />
</select>
And to make it work with the tag helper you have to implement that interface in your class:
public class Employee : IIntegerListItem
{
public int Id { get; set; }
public string FullName { get; set; }
public int Value { return Id; }
public string Text{ return FullName ; }
}
These are the needed codes:
The interface:
public interface IIntegerListItem
{
int Value { get; }
string Text { get; }
}
The <options>
tag helper:
[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
public OptionsTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
[HtmlAttributeNotBound]
public IHtmlGenerator Generator { get; set; }
[HtmlAttributeName("asp-items")]
public object Items { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.SuppressOutput();
// Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
object formDataEntry;
context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);
var selectedValues = formDataEntry as ICollection<string>;
var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (selectedValues != null && selectedValues.Count != 0)
{
foreach (var selectedValue in selectedValues)
{
encodedValues.Add(Generator.Encode(selectedValue));
}
}
IEnumerable<SelectListItem> items = null;
if (Items != null)
{
if (Items is IEnumerable)
{
var enumerable = Items as IEnumerable;
if (Items is IEnumerable<SelectListItem>)
items = Items as IEnumerable<SelectListItem>;
else if (Items is IEnumerable<IIntegerListItem>)
items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
else
throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
"<options>",
"ForAttributeName",
nameof(IModelMetadataProvider),
"For.Name"));
}
else
{
throw new InvalidOperationException("Invalid items for <options>");
}
foreach (var item in items)
{
bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
var selectedAttr = selected ? "selected='selected'" : "";
if (item.Value != null)
output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
else
output.Content.AppendHtml($"<option>{item.Text}</option>");
}
}
}
}
There may be some typo but the aim is clear I think. I had to edit a little bit.
Another option is to write to a temporary file to prevent the stdout blocking instead of needing to poll with communicate(). This worked for me where the other answers did not; for example on windows.
outFile = tempfile.SpooledTemporaryFile()
errFile = tempfile.SpooledTemporaryFile()
proc = subprocess.Popen(args, stderr=errFile, stdout=outFile, universal_newlines=False)
wait_remaining_sec = timeout
while proc.poll() is None and wait_remaining_sec > 0:
time.sleep(1)
wait_remaining_sec -= 1
if wait_remaining_sec <= 0:
killProc(proc.pid)
raise ProcessIncompleteError(proc, timeout)
# read temp streams from start
outFile.seek(0);
errFile.seek(0);
out = outFile.read()
err = errFile.read()
outFile.close()
errFile.close()
UPDATE September 2020
Facebook has new requirements change: an access token will be required for all UID-based queries
So you have to add your app access token to the url:
https://graph.facebook.com/{profile_id}/picture?type=large&access_token={app_access_token}
To get your app_access_token
use the following url:
https://graph.facebook.com/oauth/access_token?client_id={your-app-id}&client_secret={your-app-secret}&grant_type=client_credentials
You find your-app-id
and your-app-secret
in the Basic Settings of your Facebook app in Facebook developers
Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).
A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.
Those are Auto-Implemented Properties (Auto Properties for short).
The compiler will auto-generate the equivalent of the following simple implementation:
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
for what it's worth, I experienced this same error when I had a typo (md4
instead of md5
) in my pg_hba.conf
file (/etc/postgresql/9.5/main/pg_hba.conf
)
If you got here as I did, double-check that file once to make sure there isn't anything ridiculous in there.
If you doesn't want to touch the config object, you just hide the grid by css:
.chart-container .highcharts-grid {
display: none;
}
I was getting the same error. It is because your version of Pygame is not compatible with your version of Python or Pydev. Go to this link and get the proper version of Pygame for your current version of Python. Ctrl F to find it faster or click on the word python in blue. up at the top. While you instal Pygame it should find the Python path by itself. At least mind did any ways. I run Pygame through Eclipse with Python 3.4.
for me it worked by adding
1) "You can run the mongodb instance without username and password first.---OK
2) "Then you can add the user to the system database of the mongodb which is default one using the query below".---OK
db.createUser({
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ],
mechanisms:[ "SCRAM-SHA-1" ] // I added this line
})
How about a software solution:
Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.
closest()
only looks for parents, I'm guessing what you really want is .find()
$(this).closest('.row').children('.column').find('.inputQty').val();
test.matches() method checks all text.use test.find()
First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil
).
But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated:
on the wrong controller! It should be like this:
[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];
Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self
:
[self dismissModalViewControllerAnimated:YES];
If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.
I came here looking for the answer to this on OSX. I ended up getting what I wanted with bash and awk:
topfiltered() {
[[ -z "$1" ]] && return
dump="/tmp/top_dump"
rm -f "$dump"
while :; do
clear
[[ -s "$dump" ]] && head -n $(( $LINES - 1 )) "$dump"
top -l 1 -o cpu -ncols $(( $COLUMNS / 8 )) | awk -v p="$(pgrep -d ' ' $@)" '
BEGIN { split(p, arr); for (k in arr) pids[arr[k]]=1 }
NR<=12 || ($1 in pids)
' >"$dump"
done
}
I loop top in logging mode and filter it with awk, building an associative array from the output of pgrep. Awk prints the first 12 lines, where line 12 is the column headers, and then every line which has a pid that's a key in the array. The dump file is used for a more watchable loop.
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
<a href="#" id="refreshItem">Refresh</a>
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
First, Start MongoDB:
sudo service mongod start
Then, Run:
mongo
I have the following in my ~/.bash_profile
:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
If I had .bashrc
instead of ~/.bashrc
, I'd be seeing the same symptom you're seeing.
Before the closing body
tag add this (reference to jQuery library). Other hosted libraries can be found here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And this
<script>
//paste your code here
</script>
It should look something like this
<body>
........
........
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> Your code </script>
</body>
Change this property and try this at design time:
FormBorderStyle = FormBorderStyle.FixedDialog;
Designer view before the change:
Into the Preferences > Setting - Default
You will have the next by default:
// Display file encoding in the status bar
"show_encoding": false
You could change it or like cdesmetz said set your user settings.
Restoring a postgres backup file depends on how did you take the backup in the first place.
If you used pg_dump with -F c or -F d you need to use pg_restore otherwise you can just use
psql -h localhost -p 5432 -U postgres < backupfile
With POSIX Bracket Expressions (not supported by Javascript) it can be done this way:
/[:alpha:]+/
Any alpha character A to Z or a to z.
or
/^[[:alpha:]]+$/s
to match strictly with spaces.
I don't think you have what you need with:
0 0 */3 * * ## <<< WARNING!!! CAUSES UNEVEN INTERVALS AT END OF MONTH!!
Unfortunately, the */3 is setting the interval on every n day of the month and not every n days. See: explanation here. At the end of the month there is recurring issue guaranteed.
1st at 2019-02-01 00:00:00
then at 2019-02-04 00:00:00 << 3 days, etc. OK
then at 2019-02-07 00:00:00
...
then at 2019-02-25 00:00:00
then at 2019-01-28 00:00:00
then at 2019-03-01 00:00:00 << 1 day WRONG
then at 2019-03-04 00:00:00
...
According to this article, you need to add some modulo math to the command being executed to get a TRUE "every N days". For example:
0 0 * * * bash -c '(( $(date +\%s) / 86400 \% 3 == 0 )) && runmyjob.sh
In this example, the job will be checked daily at 12:00 AM, but will only execute when the number of days since 01-01-1970 modulo 3 is 0.
If you want it to be every 3 days from a specific date, use the following format:
0 0 * * * bash -c '(( $(date +\%s -d "2019-01-01") / 86400 \% 3 == 0 )) && runmyjob.sh
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
If you working with numpy, you can use the following solution which also works with negative numbers (it's also working on arrays)
import numpy as np
def round_down(num):
if num < 0:
return -np.ceil(abs(num))
else:
return np.int32(num)
round_down = np.vectorize(round_down)
round_down([-1.1, -1.5, -1.6, 0, 1.1, 1.5, 1.6])
> array([-2., -2., -2., 0., 1., 1., 1.])
I think it will also work if you just use the math
module instead of numpy
module.
You were almost done without any changes besides how you spyOn
.
When you use the spy, you have two options: spyOn
the App.prototype
, or component component.instance()
.
const spy = jest.spyOn(Class.prototype, "method")
The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.
const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);
The App.prototype
bit on the first line there are what you needed to make things work. A JavaScript class
doesn't have any of its methods until you instantiate it with new MyClass()
, or you dip into the MyClass.prototype
. For your particular question, you just needed to spy on the App.prototype
method myClickFn
.
jest.spyOn(component.instance(), "method")
const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");
This method requires a shallow/render/mount
instance of a React.Component
to be available. Essentially spyOn
is just looking for something to hijack and shove into a jest.fn()
. It could be:
A plain object
:
const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");
A class
:
class Foo {
bar() {}
}
const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance
const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.
Or a React.Component instance
:
const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");
Or a React.Component.prototype
:
/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.
I've used and seen both methods. When I have a beforeEach()
or beforeAll()
block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.
EDIT:
If you want to check the side effects of your myClickFn
you can just invoke it in a separate test.
const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/
EDIT:
Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn()
as opposed to jest.spyOn
, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.
function Component({ myClickFn, items }) {
const handleClick = (id) => {
return () => myClickFn(id);
};
return (<>
{items.map(({id, name}) => (
<div key={id} onClick={handleClick(id)}>{name}</div>
))}
</>);
}
const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);
pg_get_serial_sequence
can be used to avoid any incorrect assumptions about the sequence name. This resets the sequence in one shot:
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);
Or more concisely:
SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;
However this form can't handle empty tables correctly, since max(id) is null, and neither can you setval 0 because it would be out of range of the sequence. One workaround for this is to resort to the ALTER SEQUENCE
syntax i.e.
ALTER SEQUENCE table_name_id_seq RESTART WITH 1;
ALTER SEQUENCE table_name_id_seq RESTART; -- 8.4 or higher
But ALTER SEQUENCE
is of limited use because the sequence name and restart value cannot be expressions.
It seems the best all-purpose solution is to call setval
with false as the 3rd parameter, allowing us to specify the "next value to use":
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
This ticks all my boxes:
Finally, note that pg_get_serial_sequence
only works if the sequence is owned by the column. This will be the case if the incrementing column was defined as a serial
type, however if the sequence was added manually it is necessary to ensure ALTER SEQUENCE .. OWNED BY
is also performed.
i.e. if serial
type was used for table creation, this should all work:
CREATE TABLE t1 (
id serial,
name varchar(20)
);
SELECT pg_get_serial_sequence('t1', 'id'); -- returns 't1_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
But if sequences were added manually:
CREATE TABLE t2 (
id integer NOT NULL,
name varchar(20)
);
CREATE SEQUENCE t2_custom_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass);
ALTER SEQUENCE t2_custom_id_seq OWNED BY t2.id; -- required for pg_get_serial_sequence
SELECT pg_get_serial_sequence('t2', 'id'); -- returns 't2_custom_id_seq'
-- reset the sequence, regardless whether table has rows or not:
SELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1;
As has already been pointed out, array size is limited by your hardware and your OS (man ulimit). Your software though, may only be limited by your creativity. For example, can you store your "array" on disk? Do you really need long long ints? Do you really need a dense array? Do you even need an array at all?
One simple solution would be to use 64 bit Linux. Even if you do not physically have enough ram for your array, the OS will allow you to allocate memory as if you do since the virtual memory available to your process is likely much larger than the physical memory. If you really need to access everything in the array, this amounts to storing it on disk. Depending on your access patterns, there may be more efficient ways of doing this (ie: using mmap(), or simply storing the data sequentially in a file (in which case 32 bit Linux would suffice)).
Currently the easiest way to do this on Mac and Windows is using host host.docker.internal
, that resolves to host machine's IP address. Unfortunately it does not work on linux yet (as of April 2018).
As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.
Example:
Say you have an Animal
class something like
class Animal{
private String name;
private String type;
}
Lets see what happens when you try to create an instance of Animal class, say a Dog
named Puppy
. Now you have have to initialize name = Puppy
and type = Dog
. So, how can you do that. A way of doing it is having a constructor like
Animal(String nameProvided, String typeProvided){
this.name = nameProvided;
this.type = typeProvided;
}
Now when you create an object of class Animal
, something like Animal dog = new Animal("Puppy", "Dog");
your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.
Now you might ask what if I didn't provide an argument to my constructor something like
Animal xyz = new Animal();
This is a default Constructor
which initializes the object with default values i.e. in our Animal
class name
and type
values corresponding to xyz
object would be name = null
and type = null
We had similar problem - status code 0 on jquery ajax call - and it took us whole day to diagnose it. Since no one had mentioned this reason yet, I thought I'll share.
In our case the problem was HTTP server crash. Some bug in PHP was blowing Apache, so on client end it looked like this:
mirek@toccata:~$ telnet our.server.com 80
Trying 180.153.xxx.xxx...
Connected to our.server.com.
Escape character is '^]'.
GET /test.php HTTP/1.0
Host: our.server.com
Connection closed by foreign host.
mirek@toccata:~$
where test.php contained the crashing code. No data returned from the server (not even headers) => ajax call was aborted with status 0.
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
You want to run:
php -m
on the command line,
or if you have access to the server configuration file open
/etc/php5/apache2/php.ini
and look at all the the extensions,
you can even enable or disable them by switching between On and Off like this
<Extension_name> = <[On | Off]>
AppCompat doesn't do that for dialogs (not yet at least)
EDIT: it does now. make sure to use android.support.v7.app.AlertDialog
Using crosstab
, this will return more information than groupby
nunique
pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]:
CLIENTCODE 1 2 3
YEARMONTH
201301 2 1 0
201302 1 2 1
After a little bit modify ,yield the result
pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]:
YEARMONTH
201301 2
201302 3
dtype: int64
See Converting unix timestamp to excel date-time forum thread.
You can use jQuery's $.Deferred
var FunctionOne = function () {
// create a deferred object
var r = $.Deferred();
// do whatever you want (e.g. ajax/animations other asyc tasks)
setTimeout(function () {
// and call `resolve` on the deferred object, once you're done
r.resolve();
}, 2500);
// return the deferred object
return r;
};
// define FunctionTwo as needed
var FunctionTwo = function () {
console.log('FunctionTwo');
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
you could also pack multiple deferreds together:
var FunctionOne = function () {
var
a = $.Deferred(),
b = $.Deferred();
// some fake asyc task
setTimeout(function () {
console.log('a done');
a.resolve();
}, Math.random() * 4000);
// some other fake asyc task
setTimeout(function () {
console.log('b done');
b.resolve();
}, Math.random() * 4000);
return $.Deferred(function (def) {
$.when(a, b).done(function () {
def.resolve();
});
});
};
My version, in my humble opinion, more readable:
SELECT PARENT.TABLE_NAME "PARENT TABLE_NAME"
, PARENT.CONSTRAINT_NAME "PARENT PK CONSTRAINT"
, '->' " "
, CHILD.TABLE_NAME "CHILD TABLE_NAME"
, CHILD.COLUMN_NAME "CHILD COLUMN_NAME"
, CHILD.CONSTRAINT_NAME "CHILD CONSTRAINT_NAME"
FROM ALL_CONS_COLUMNS CHILD
, ALL_CONSTRAINTS CT
, ALL_CONSTRAINTS PARENT
WHERE CHILD.OWNER = CT.OWNER
AND CT.CONSTRAINT_TYPE = 'R'
AND CHILD.CONSTRAINT_NAME = CT.CONSTRAINT_NAME
AND CT.R_OWNER = PARENT.OWNER
AND CT.R_CONSTRAINT_NAME = PARENT.CONSTRAINT_NAME
AND CHILD.TABLE_NAME = ::table -- table name variable
AND CT.OWNER = ::owner; -- schema variable, could not be needed
This works really fine:
\+?\d[\d -]{8,12}\d
Matches:
03598245785
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
987-98723-9898
+91 98780 98802
06421223054
9934-05-4851
WAQU9876567892
ABCD9876541212
98723-98765
Does NOT match:
2343
234-8700
1 234 765
UPDATE Table SET Column = REPLACE(Column, char(9), '')
Not the most beautiful way of doing it I guess:
git log --pretty=oneline | wc -l
This gives you a number then
git log HEAD~<The number minus one>
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026
Now you should use:
http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.
For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.
So in the end you would have an URL like this:
http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg
I ran into issues on one of my servers querying MSDB tables (aka code listed above) as one of my jobs would come up running, but it was not. There is a system stored procedure that returns the execution status, but one cannot do a insert exec statement without an error. Inside that is another system stored procedure that can be used with an insert exec statement.
INSERT INTO #Job
EXEC master.dbo.xp_sqlagent_enum_jobs 1,dbo
And the table to load it into:
CREATE TABLE #Job
(job_id UNIQUEIDENTIFIER NOT NULL,
last_run_date INT NOT NULL,
last_run_time INT NOT NULL,
next_run_date INT NOT NULL,
next_run_time INT NOT NULL,
next_run_schedule_id INT NOT NULL,
requested_to_run INT NOT NULL, -- BOOL
request_source INT NOT NULL,
request_source_id sysname COLLATE database_default NULL,
running INT NOT NULL, -- BOOL
current_step INT NOT NULL,
current_retry_attempt INT NOT NULL,
job_state INT NOT NULL)
Just a little more clarification: A property without 'get','set' won't be able to be bound
I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:
//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
public String My_Property { get; set; }
...
//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
...
public my_class() {
My_Property = "my-string-value";
InitializeComponent();
}
//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding My_Property}"/>
</Window>
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
I am surprised no one mentioned hsearch/hcreate set of libraries which although is not available on windows, but is mandated by POSIX, and therefore available in Linux / GNU systems.
The link has a simple and complete basic example that very well explains its usage.
It even has thread safe variant, is easy to use and very performant.
you spelt it wrongly, it should be " getElementsByClassName ",
var objs = document.getElementsByClassName("stopButton");
var stopMusicExt = objs[0]; //retrieve the first node in the stack
//your remaining function goes down here..
document['player'].stopMusicExt(ta.value);
ta.value = "";
document.getElementsByClassName - returns a stack of nodes with more than one item, since CLASS attributes are used to assign to multiple objects...
There’s a nice approach to this problem that uses vector cross products. Define the 2-dimensional vector cross product v × w to be vx wy - vy wx.
Suppose the two line segments run from p to p + r and from q to q + s. Then any point on the first line is representable as p + t r (for a scalar parameter t) and any point on the second line as q + u s (for a scalar parameter u).
The two lines intersect if we can find t and u such that:
p + t r = q + u s
Cross both sides with s, getting
(p + t r) × s = (q + u s) × s
And since s × s = 0, this means
t (r × s) = (q - p) × s
And therefore, solving for t:
t = (q - p) × s / (r × s)
In the same way, we can solve for u:
(p + t r) × r = (q + u s) × r
u (s × r) = (p - q) × r
u = (p - q) × r / (s × r)
To reduce the number of computation steps, it's convenient to rewrite this as follows (remembering that s × r = - r × s):
u = (q - p) × r / (r × s)
Now there are four cases:
If r × s = 0 and (q - p) × r = 0, then the two lines are collinear.
In this case, express the endpoints of the second segment (q and q + s) in terms of the equation of the first line segment (p + t r):
t0 = (q - p) · r / (r · r)
t1 = (q + s - p) · r / (r · r) = t0 + s · r / (r · r)
If the interval between t0 and t1 intersects the interval [0, 1] then the line segments are collinear and overlapping; otherwise they are collinear and disjoint.
Note that if s and r point in opposite directions, then s · r < 0 and so the interval to be checked is [t1, t0] rather than [t0, t1].
If r × s = 0 and (q - p) × r ? 0, then the two lines are parallel and non-intersecting.
If r × s ? 0 and 0 = t = 1 and 0 = u = 1, the two line segments meet at the point p + t r = q + u s.
Otherwise, the two line segments are not parallel but do not intersect.
Credit: this method is the 2-dimensional specialization of the 3D line intersection algorithm from the article "Intersection of two lines in three-space" by Ronald Goldman, published in Graphics Gems, page 304. In three dimensions, the usual case is that the lines are skew (neither parallel nor intersecting) in which case the method gives the points of closest approach of the two lines.
Nobody mentioned one crucial difference, ironically answered on a question closed as a duplicated of this.
IEnumerable is read-only and List is not.
alert('Alert For your User!') ? "" : location.reload();
You can write above code in this format also.It seems quite decent
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
Time and Space complexity are different aspects of calculating the efficiency of an algorithm.
Time complexity deals with finding out how the computational time of an algorithm changes with the change in size of the input.
On the other hand, space complexity deals with finding out how much (extra)space would be required by the algorithm with change in the input size.
To calculate time complexity of the algorithm the best way is to check if we increase in the size of the input, will the number of comparison(or computational steps) also increase and to calculate space complexity the best bet is to see additional memory requirement of the algorithm also changes with the change in the size of the input.
A good example could be of Bubble sort.
Lets say you tried to sort an array of 5 elements. In the first pass you will compare 1st element with next 4 elements. In second pass you will compare 2nd element with next 3 elements and you will continue this procedure till you fully exhaust the list.
Now what will happen if you try to sort 10 elements. In this case you will start with comparing comparing 1st element with next 9 elements, then 2nd with next 8 elements and so on. In other words if you have N element array you will start of by comparing 1st element with N-1 elements, then 2nd element with N-2 elements and so on. This results in O(N^2)
time complexity.
But what about size. When you sorted 5 element or 10 element array did you use any additional buffer or memory space. You might say Yes, I did use a temporary variable to make the swap. But did the number of variables changed when you increased the size of array from 5 to 10. No, Irrespective of what is the size of the input you will always use a single variable to do the swap. Well, this means that the size of the input has nothing to do with the additional space you will require resulting in O(1)
or constant space complexity.
Now as an exercise for you, research about the time and space complexity of merge sort
I was getting ó in $mail->Subject /w PHPMailer.
So for me the complete solution is:
// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';
$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);
Hope it helps.
Really the ideal way to do this is to not use pull
at all, but instead fetch
and reset
:
git fetch origin master
git reset --hard FETCH_HEAD
git clean -df
(Altering master
to whatever branch you want to be following.)
pull
is designed around merging changes together in some way, whereas reset
is designed around simply making your local copy match a specific commit.
You may want to consider slightly different options to clean
depending on your system's needs.
.at-counter-box {
border: 2px solid #1ac6ff;
width: 150px;
height: 150px;
border-radius: 100px;
font-family: 'Oswald Sans', sans-serif;
color:#000;
}
.at-counter-box-content {
position: relative;
}
.at-counter-content span {
font-size: 40px;
font-weight: bold ;
text-align: center;
position: relative;
top: 55px;
}
Click Build tab ---> Clean Project
Click Build tab ---> Build APK
Run.
How about str.split()? Nothing to import.
import os
image_names = [f for f in os.listdir(path) if len(f.split('.jpg')) == 2]