Try PyPDF2.
There is a good tutorial here: https://automatetheboringstuff.com/chapter13/
$(document).ready(function(){
$('input.checkD[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$(this).val('true');
}
else if($(this).prop("checked") == false){
$(this).val('false');
}
});
});
this worked for me..
<Location />
Allow from all
Order Deny,Allow
</Location>
I have included this code in my /etc/apache2/apache2.conf
Using regex and find&replace, you can delete all the lines containing #region without leaving empty lines.
Because for some reason Ray's method didn't work on my machine I searched for (.*#region.*\n)|(\n.*#region.*)
and left the replace box empty.
That regex ensures that the if #region
is found on the first line, the ending newline is deleted, and if it is found on the last line the preceding newline is deleted.
Still, Ray's solution is the better one if it works for you.
Oh, really a long list of answers. It helped a lot and finally, I created my own which I was looking for :
To List All the Files in a directory and its sub-directories:
find "$PWD" -type f
To List All the Directories in a directory and its sub-directories:
find "$PWD" -type d
To List All the Directories and Files in a directory and its sub-directories:
find "$PWD"
The opposite of the ==
compare operator is !=
.
How can I create a copy of an object in Python?
So, if I change values of the fields of the new object, the old object should not be affected by that.
You mean a mutable object then.
In Python 3, lists get a copy
method (in 2, you'd use a slice to make a copy):
>>> a_list = list('abc')
>>> a_copy_of_a_list = a_list.copy()
>>> a_copy_of_a_list is a_list
False
>>> a_copy_of_a_list == a_list
True
Shallow copies are just copies of the outermost container.
list.copy
is a shallow copy:
>>> list_of_dict_of_set = [{'foo': set('abc')}]
>>> lodos_copy = list_of_dict_of_set.copy()
>>> lodos_copy[0]['foo'].pop()
'c'
>>> lodos_copy
[{'foo': {'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
You don't get a copy of the interior objects. They're the same object - so when they're mutated, the change shows up in both containers.
Deep copies are recursive copies of each interior object.
>>> lodos_deep_copy = copy.deepcopy(list_of_dict_of_set)
>>> lodos_deep_copy[0]['foo'].add('c')
>>> lodos_deep_copy
[{'foo': {'c', 'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
Changes are not reflected in the original, only in the copy.
Immutable objects do not usually need to be copied. In fact, if you try to, Python will just give you the original object:
>>> a_tuple = tuple('abc')
>>> tuple_copy_attempt = a_tuple.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'copy'
Tuples don't even have a copy method, so let's try it with a slice:
>>> tuple_copy_attempt = a_tuple[:]
But we see it's the same object:
>>> tuple_copy_attempt is a_tuple
True
Similarly for strings:
>>> s = 'abc'
>>> s0 = s[:]
>>> s == s0
True
>>> s is s0
True
and for frozensets, even though they have a copy
method:
>>> a_frozenset = frozenset('abc')
>>> frozenset_copy_attempt = a_frozenset.copy()
>>> frozenset_copy_attempt is a_frozenset
True
Immutable objects should be copied if you need a mutable interior object copied.
>>> tuple_of_list = [],
>>> copy_of_tuple_of_list = tuple_of_list[:]
>>> copy_of_tuple_of_list[0].append('a')
>>> copy_of_tuple_of_list
(['a'],)
>>> tuple_of_list
(['a'],)
>>> deepcopy_of_tuple_of_list = copy.deepcopy(tuple_of_list)
>>> deepcopy_of_tuple_of_list[0].append('b')
>>> deepcopy_of_tuple_of_list
(['a', 'b'],)
>>> tuple_of_list
(['a'],)
As we can see, when the interior object of the copy is mutated, the original does not change.
Custom objects usually store data in a __dict__
attribute or in __slots__
(a tuple-like memory structure.)
To make a copyable object, define __copy__
(for shallow copies) and/or __deepcopy__
(for deep copies).
from copy import copy, deepcopy
class Copyable:
__slots__ = 'a', '__dict__'
def __init__(self, a, b):
self.a, self.b = a, b
def __copy__(self):
return type(self)(self.a, self.b)
def __deepcopy__(self, memo): # memo is a dict of id's to copies
id_self = id(self) # memoization avoids unnecesary recursion
_copy = memo.get(id_self)
if _copy is None:
_copy = type(self)(
deepcopy(self.a, memo),
deepcopy(self.b, memo))
memo[id_self] = _copy
return _copy
Note that deepcopy
keeps a memoization dictionary of id(original)
(or identity numbers) to copies. To enjoy good behavior with recursive data structures, make sure you haven't already made a copy, and if you have, return that.
So let's make an object:
>>> c1 = Copyable(1, [2])
And copy
makes a shallow copy:
>>> c2 = copy(c1)
>>> c1 is c2
False
>>> c2.b.append(3)
>>> c1.b
[2, 3]
And deepcopy
now makes a deep copy:
>>> c3 = deepcopy(c1)
>>> c3.b.append(4)
>>> c1.b
[2, 3]
I started getting this problem when I started using rbenv with Ruby 1.9.3 where as my system ruby is 1.8.7. The gem is installed in both places but for some reason the rails script didn't pick it up. But adding the "execjs" and "therubyracer" to the Gemfile did the trick.
You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:
CREATE TABLE #tmp(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(1000);
SET @sql = N'BULK INSERT #tmp ...' + @variables;
EXEC master.sys.sp_executesql @sql;
SELECT * FROM #tmp;
This makes it tougher to maintain (readability) but gets by the scoping issue:
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
BULK INSERT #tmp ...' + @variables + ';
SELECT * FROM #tmp;';
EXEC master.sys.sp_executesql @sql;
EDIT 2011-01-12
In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:
CREATE TABLE #outer(a INT, b INT, c INT);
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SET NOCOUNT ON;
CREATE TABLE #inner(a INT, b INT, c INT);
BULK INSERT #inner ...' + @variables + ';
SELECT * FROM #inner;';
INSERT #outer EXEC master.sys.sp_executesql @sql;
Use a std::wstring
instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string
. E.g.,
std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );
C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.
With that change your function return type should also be std::wstring
.
Remember to set relevant locale in main
.
E.g., setlocale( LC_ALL, "" )
.
Cheers & hth.,
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
create table encrypt(username varchar(20),password varbinary(200))
insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';
In bash 4, you can use associative arrays:
declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
echo "key: $key, value: ${foo[$key]}"
done
# output
# $ key: 0, value bar.
# $ key: 35, value baz.
In bash 3, this works (also works in zsh):
map=( )
map+=("0:bar")
map+=("35:baz")
for keyvalue in "${map[@]}" ; do
key=${keyvalue%%:*}
value=${keyvalue#*:}
echo "key: $key, value $value."
done
"Concurrency" is when there are multiple things in progress.
"Parallelism" is when concurrent things are progressing at the same time.
Examples of concurrency without parallelism:
SqlDataReader
s on a MARS connection.Note, however, that the difference between concurrency and parallelism is often a matter of perspective. The above examples are non-parallel from the perspective of (observable effects of) executing your code. But there is instruction-level parallelism even within a single core. There are pieces of hardware doing things in parallel with CPU and then interrupting the CPU when done. GPU could be drawing to screen while you window procedure or event handler is being executed. The DBMS could be traversing B-Trees for the next query while you are still fetching the results of the previous one. Browser could be doing layout or networking while your Promise.resolve()
is being executed. Etc, etc...
So there you go. The world is as messy as always ;)
Now you may see trash icon and DELETE PROJECT button.
df.replace('columnvalue',np.NaN,inplace=True)
You need to add a name to your <select>
element:
<select id="testSelect" name="testSelect">
It will be posted to the server, and you can see it using:
Request.Form["testSelect"]
player['score']
is your problem. player is apparently a list
which means that there is no 'score' element. Instead you would do something like:
name, score = player[0], player[1]
return name + ' ' + str(score)
Of course, you would have to know the list indices (those are the 0 and 1 in my example).
Something like player['score']
is allowed in python, but player
would have to be a dict
.
You can read more about both lists and dicts in the python documentation.
Try to remove ib_logfile0
and ib_logfile1
files and then run mysql again
rm /usr/local/var/mysql/ib_logfile0
rm /usr/local/var/mysql/ib_logfile1
It works for me.
If anyone is still looking for an easy way to decompile an APK (with resource decompiling), have a look at the tools I have created: https://github.com/dirkvranckaert/AndroidDecompiler
Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.
Primary key does not allow NULL
values, but unique key allows NULL
values.
We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).
wamp\bin\php
directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp
Make sure to throw on the !important
for Outlook especially.
td {
border-collapse: separate;
padding: 15 !important
}
I also wanted borders, so might not work for someone who doesn't.
Native tooltip cannot be styled.
That being said, you can use some library that would show styles floating layers when element is being hovered (instead of the native tooltips, and suppress them) requiring little or no code modifications...
If you want to keep your version same like rails will be 2.3.8 and gem version will be latest. You can use this solution Latest gem with Rails2.x. in this some changes in boot.rb file and environment.rb file.
require 'thread
' in boot.rb file at the top.
and in environment.rb file add the following code above the initializer block.
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.3.7')
module Rails
class GemDependency
def requirement
r = super
(r == Gem::Requirement.default) ? nil : r
end
end
end
end
Check if the activity isFinishing()
before showing the fragment.
Example:
if(!isFinishing()) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DummyFragment dummyFragment = DummyFragment.newInstance();
ft.add(R.id.dummy_fragment_layout, dummyFragment);
ft.commitAllowingStateLoss();
}
You can set your content-type header so clients know to expect json
w.Header().Set("Content-Type", "application/json")
Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter
// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)
I had same error. And in my case
REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.
SOLUTION: give access to user for resourses or remove restriction at all.
$emit
It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $emit
was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.
$broadcast
It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope
listeners. The event life cycle starts at the scope on which $broadcast
was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.
$on
It listen on events of a given type. It can catch the event dispatched by $broadcast
and $emit
.
Visual demo:
Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview
Demonstrates the method calls:
$scope.$on('eventEmitedName', function(event, data) ...
$scope.broadcastEvent
$scope.emitEvent
$('#id span').text()
is the answer!
Create the war file in a different directory to where the content is otherwise the jar command might try to zip up the file it is creating.
#!/bin/bash
set -euo pipefail
war=app.war
src=contents
# Clean last war build
if [ -e ${war} ]; then
echo "Removing old war ${war}"
rm -rf ${war}
fi
# Build war
if [ -d ${src} ]; then
echo "Found source at ${src}"
cd ${src}
jar -cvf ../${war} *
cd ..
fi
# Show war details
ls -la ${war}
Another way would be to use glue
package:
glue_collapse(glue("{sdata}"))
paste(glue("{sdata}"), collapse = '')
data, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(data))
The syntax is:
=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])
=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)
For instance if you'd like to convert the rate on specific date, here is some more advanced example:
=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))
where $A2
is your date (e.g. 01/01/2015
) and C2
is your currency (e.g. EUR
).
See more samples at Docs editors Help at Google.
In XCode 7.3
I encountered the same question, I 've made the mistake because:
Name in (info.plist -->Bundle identifier
) is not the same as (target-->build settings -->packaging-->Product bundle identifier
). Just make the same, that solved the problem.
I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test
in my Mac(10.15.2), I ran gdb
with the executable in Ubuntu(16.04) in my VirtualBox.
Fix: recompile with the same command under Ubuntu, then you should be good.
I sometimes use (in Load)
this.BeginInvoke((MethodInvoker) delegate {
// some code
});
or
this.BeginInvoke((MethodInvoker) this.SomeMethod);
(change "this" to your form variable if you are handling the event on an instance other than "this").
This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.
[updated on request]
The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.
Normally, these would be used as:
SomeCodeOrEventHandlerOnAWorkerThread()
{
// this code running on a worker thread...
string newText = ExpensiveMethod(); // perhaps a DB/web call
// now ask the UI thread to update itself
this.Invoke((MethodInvoker) delegate {
// this code runs on the UI thread!
this.Text = newText;
});
}
It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p
OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...
But Control.BeginInvoke works differently: it always pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).
If you have a list with 53 items, the last one is thelist[52]
because indexing starts at 0.
IndexError
IndexError
The IndexError
is raised when attempting to retrieve an index from a sequence (e.g. list
, tuple
), and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:
Raised when a sequence subscript is out of range. (Source)
Here’s an example that raises the IndexError
:
test = list(range(53))
test[53]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
1 test = list(range(53))
----> 2 test[53]
IndexError: list index out of range
The error message line for an IndexError
doesn’t provide great information. See that there is a sequence reference that is out of range and what the type of the sequence is, a list
in this case. That information, combined with the rest of the traceback, is usually enough to help quickly identify how to fix the issue.
With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.
Thanks
Note : This is by no means the best possible way to do it!
Situation : I had to do the same thign only i was not able to add any extra divs, therefore i was stuck with what i had and rather than removing innerHTML and creating another via javascript almost like 2 renders i needed to have the content at the bottom (animated bar).
Solution: Given how tired I was at the time its seems normal to even think of such a method however I knew i had a parent DOM element which the bar's height was starting from.
Rather than messing with the javascript any further i used a (NOT ALWAYS GOOD IDEA) CSS answer! :)
-moz-transform:rotate(180deg);
-webkit-transform:rotate(180deg);
-ms-transform:rotate(180deg);
Yes thats correct, instead of positioning the DOM, i turned its parent upside down in css.
For my scenario it will work! Possibly for others too ! No Flame! :)
The Java keyword list specifies the goto keyword, but it is marked as "not used".
This was probably done in case it were to be added to a later version of Java.
If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
height
for td
works like min-height
:
td {
height: 100px;
}
instead of
td {
min-height: 100px;
}
Table cells will grow when the content does not fit.
I had very similar situation (had a project on another machine and cloned it to my laptop and saw the same issue) and I looked in it.
Error message was coming from Sdk.groovy
of Android gradle plugin:
https://android.googlesource.com/platform/tools/build/+/master/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy
By looking at code, its findLocation
needs to set androidSdkDir
variable and there are only three ways to do it:
local.properties
file and have either sdk.dir
or android.dir
line.ANDROID_HOME
environment variable defined.While your Android Studio knows that the SDK is at that place, I doubt that Android Studio is passing that information to gradle and thus we're seeing that error.
I created local.properties
file at the project root and put the following line and it compiled the code successfully.
sdk.dir = /Applications/Android Studio.app/sdk/
If you want to force the factory function usage, name your struct (your class) with the first character in lowercase. Then, it won't be possible to instantiate directly the struct, the factory method will be required.
This visibility based on first character lower/upper case work also for struct field and for the function/method. If you don't want to allow external access, use lower case.
The best way I have found to do this, if you want to fully customize the button is to create a button, or any View you want (in my case it was a LinearLayout
) and set an OnClickListener
to that view, and call the following in the onClick event:
com.facebook.login.widget.LoginButton btn = new LoginButton(this);
btn.performClick();
Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.
This is what you need to do:
Some benefits of using classes instead of :nth-child
is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.
I've tested it on all Chrome, Firefox and IE11:
.main-stop {_x000D_
stop-color: red;_x000D_
}_x000D_
.alt-stop {_x000D_
stop-color: green;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<linearGradient id="gradient">_x000D_
<stop class="main-stop" offset="0%" />_x000D_
<stop class="alt-stop" offset="100%" />_x000D_
</linearGradient>_x000D_
<rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>
_x000D_
See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output
Found the answer. In the file xampp\apache\conf\extra\httpd-ssl.conf
, under the comment SSL Virtual Host Context
pages on port 443 meaning https is looked up under different document root.
Simply change the document root to the same one and problem is fixed.
You can approach it from either an "allow list" or a "block list" way:
// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);
// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
If it's reusable business logic, you can partial it out as well:
// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);
// and later
var result = clean(credentials);
A similar approach can be achieved without Lodash:
const transform = (obj, predicate) => {
return Object.keys(obj).reduce((memo, key) => {
if(predicate(obj[key], key)) {
memo[key] = obj[key]
}
return memo
}, {})
}
const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])
// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])
// "App"
const credentials = {
fname:"xyz",
lname:"abc",
age:23
}
const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)
As P0W has provided complete syntax for each C++ version, I would like to add couple of more points by looking at your code
const &
as argument as to avoid extra copies of the same object.unordered_map
as its always faster to use. See this discussionhere is a sample code:
#include <iostream>
#include <unordered_map>
using namespace std;
void output(const auto& table)
{
for (auto const & [k, v] : table)
{
std::cout << "Key: " << k << " Value: " << v << std::endl;
}
}
int main() {
std::unordered_map<string, int> mydata = {
{"one", 1},
{"two", 2},
{"three", 3}
};
output(mydata);
return 0;
}
You can use ES6 backtick syntax too
<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>
Also note that a result code in the second column refers to the properties of the file. For example:
U filename.1
U filename.2
UU filename.3
filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated
To select rows whose column value equals a scalar, some_value
, use ==
:
df.loc[df['column_name'] == some_value]
To select rows whose column value is in an iterable, some_values
, use isin
:
df.loc[df['column_name'].isin(some_values)]
Combine multiple conditions with &
:
df.loc[(df['column_name'] >= A) & (df['column_name'] <= B)]
Note the parentheses. Due to Python's operator precedence rules, &
binds more tightly than <=
and >=
. Thus, the parentheses in the last example are necessary. Without the parentheses
df['column_name'] >= A & df['column_name'] <= B
is parsed as
df['column_name'] >= (A & df['column_name']) <= B
which results in a Truth value of a Series is ambiguous error.
To select rows whose column value does not equal some_value
, use !=
:
df.loc[df['column_name'] != some_value]
isin
returns a boolean Series, so to select rows whose value is not in some_values
, negate the boolean Series using ~
:
df.loc[~df['column_name'].isin(some_values)]
For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['A'] == 'foo'])
yields
A B C D
0 foo one 0 0
2 foo two 2 4
4 foo two 4 8
6 foo one 6 12
7 foo three 7 14
If you have multiple values you want to include, put them in a
list (or more generally, any iterable) and use isin
:
print(df.loc[df['B'].isin(['one','three'])])
yields
A B C D
0 foo one 0 0
1 bar one 1 2
3 bar three 3 6
6 foo one 6 12
7 foo three 7 14
Note, however, that if you wish to do this many times, it is more efficient to
make an index first, and then use df.loc
:
df = df.set_index(['B'])
print(df.loc['one'])
yields
A C D
B
one foo 0 0
one bar 1 2
one foo 6 12
or, to include multiple values from the index use df.index.isin
:
df.loc[df.index.isin(['one','two'])]
yields
A C D
B
one foo 0 0
one bar 1 2
two foo 2 4
two foo 4 8
two bar 5 10
one foo 6 12
SELECT IFNULL(SUM(Column1), 0) AS total FROM...
SELECT COALESCE(SUM(Column1), 0) AS total FROM...
The difference between them is that IFNULL
is a MySQL extension that takes two arguments, and COALESCE
is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL
is slightly faster, though here the difference is insignificant since it is only called once.
If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[]
or List
. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.
EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.
Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.
(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)
To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
If you're using a scanner, in your scanner try to have it return the least number of qualifiers as possible. In fact, the qualifier(s) that you do return should be the smallest (in byte-size) as you have available. This will speed up your scan tremendously.
Unfortuneately this will only scale so far (millions-billions?). To take it further, you can do this in real time but you will first need to run a mapreduce job to count all rows.
Store the Mapreduce output in a cell in HBase. Every time you add a row, increment the counter by 1. Every time you delete a row, decrement the counter.
When you need to access the number of rows in real time, you read that field in HBase.
There is no fast way to count the rows otherwise in a way that scales. You can only count so fast.
open(filename,'r') #2nd argument is r and not w
will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error
try:
open(filename,'r')
return True
except IOError:
try:
open(filename, 'w')
return True
except IOError:
return False
Also have a look here about permissions on windows
For anyone else having the same problem, I figured it out myself.
<html>_x000D_
<body>_x000D_
<form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
<input type="hidden" name="fullname" value="Sam" />_x000D_
<input type="hidden" name="city" value="Dubai " />_x000D_
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
Depending on why you are doing this, using a std::set might be a better idea than std::vector.
It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.
This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.
You can both highlight and select the item with the following 1-liner:
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
Long form:
get-content env:computername
Short form:
gc env:computername
public static class ArrayExtensions
{
public static int MaxIndexOf<T>(this T[] input)
{
var max = input.Max();
int index = Array.IndexOf(input, max);
return index;
}
}
This works for all variable types...
var array = new int[]{1, 2, 4, 10, 0, 2};
var index = array.MaxIndexOf();
var array = new double[]{1.0, 2.0, 4.0, 10.0, 0.0, 2.0};
var index = array.MaxIndexOf();
Use in AppDelegate.m
file:
(void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
NSLog(@"Selected index: %d", tabBarController.selectedIndex);
if (viewController == tabBarController.moreNavigationController)
{
tabBarController.moreNavigationController.delegate = self;
}
NSUInteger selectedIndex = tabBarController.selectedIndex;
switch (selectedIndex) {
case 0:
NSLog(@"click me %u",self.tabBarController.selectedIndex);
break;
case 1:
NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
break;
default:
break;
}
}
Try this code
HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");
I made a basic Demo and reproduced this problem. It seems that WinRT component failed to find the correct assembly of Newton.Json
. Temporarily the workaround is to manually add the Newtonsoft.json.dll
file. You can achieve this by following steps:
Right click References-> Add Reference->Browse...-> Find C:\Users\.nuget\packages\Newtonsoft.Json\9.0.1\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.json.dll->Click Add button.
Rebuild your Runtime Component project and run. This error should be gone.
In my case I am using a CSS framework which adds box-shadow
, so I had to also add
box-shadow: none;
So the complete snippet is:
border: none;
border-width: 0;
box-shadow: none;
The CSS property that can be used is:
pointer-events:none
!IMPORTANT Keep in mind that this property is not supported by Opera Mini and IE 10 and below (inclusive). Another solution is needed for these browsers.
jQuery METHOD If you want to disable it via script and not CSS property, these can help you out: If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
You can re-enable clicks with pointer-events: auto;
(Documentation)
Note that pointer-events
overrides the cursor
property, so if you want the cursor to be something other than the standard , your css should be place after pointer-events
.
Pandas has the itertuples
method to do exactly this:
list(df[['lat', 'long']].itertuples(index=False, name=None))
This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.
To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)
To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)
Like the frame, view.center is also in the coordinates of the superview.
The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.
Frame
origin = (0, 0)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60) // That is, x=40 and y=60
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (20, 52) // These are just rough estimates.
width = 118
height = 187
Bounds
origin = (0, 0)
width = 80
height = 130
This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (280, 70)
width = 80
height = 130
Again, see here for my answer with more details.
Configuration files are application-scoped and not assembly-scoped. So you'll need to put your library's configuration sections in every application's configuration file that is using your library.
That said, it is not a good practice to get configuration from the application's configuration file, specially the appSettings
section, in a class library. If your library needs parameters, they should probably be passed as method arguments in constructors, factory methods, etc. by whoever is calling your library. This prevents calling applications from accidentally reusing configuration entries that were expected by the class library.
That said, XML configuration files are extremely handy, so the best compromise that I've found is using custom configuration sections. You get to put your library's configuration in an XML file that is automatically read and parsed by the framework and you avoid potential accidents.
You can learn more about custom configuration sections on MSDN and also Phil Haack has a nice article on them.
If you have the width set in the viewport :
<meta name = "viewport" content = "width=device-width; initial-scale=1.0;
maximum-scale=1.0;" />
And then change the orientation it will randomly zoom in sometimes (especially if you are dragging on the screen) to fix this don't set a width here I used :
<meta id="viewport" name="viewport" content="initial-scale=1.0; user-scalable=0;
minimum-scale=1.0; maximum-scale=1.0" />
This fixes the zoom whatever happens then you can use either window.onorientationchange event or if you want it to be platform independant (handy for testing) the window.innerWidth method.
One approach could be using find:
find /desired_location -type d -print0 | xargs -0 chmod 0755
find /desired_location -type f -print0 | xargs -0 chmod 0644
I used org.json built-in methods to pretty-print the data.
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
The order of fields in JSON is random per definition. A specific order is subject to parser implementation.
The special thing about iterators is that they provide the glue between algorithms and containers. For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find
, sort
, remove
, copy
) etc. that carries out the computation that you have in mind on your data structure (vector
, list
, map
etc.), and to supply that algorithm with iterators into your container.
Your particular example could be written as a combination of the for_each
algorithm and the vector
container (see option 3) below), but it's only one out of four distinct ways to iterate over a std::vector:
1) index-based iteration
for (std::size_t i = 0; i != v.size(); ++i) {
// access element as v[i]
// any code including continue, break, return
}
Advantages: familiar to anyone familiar with C-style code, can loop using different strides (e.g. i += 2
).
Disadvantages: only for sequential random access containers (vector
, array
, deque
), doesn't work for list
, forward_list
or the associative containers. Also the loop control is a little verbose (init, check, increment). People need to be aware of the 0-based indexing in C++.
2) iterator-based iteration
for (auto it = v.begin(); it != v.end(); ++it) {
// if the current index is needed:
auto i = std::distance(v.begin(), it);
// access element as *it
// any code including continue, break, return
}
Advantages: more generic, works for all containers (even the new unordered associative containers, can also use different strides (e.g. std::advance(it, 2)
);
Disadvantages: need extra work to get the index of the current element (could be O(N) for list or forward_list). Again, the loop control is a little verbose (init, check, increment).
3) STL for_each algorithm + lambda
std::for_each(v.begin(), v.end(), [](T const& elem) {
// if the current index is needed:
auto i = &elem - &v[0];
// cannot continue, break or return out of the loop
});
Advantages: same as 2) plus small reduction in loop control (no check and increment), this can greatly reduce your bug rate (wrong init, check or increment, off-by-one errors).
Disadvantages: same as explicit iterator-loop plus restricted possibilities for flow control in the loop (cannot use continue, break or return) and no option for different strides (unless you use an iterator adapter that overloads operator++
).
4) range-for loop
for (auto& elem: v) {
// if the current index is needed:
auto i = &elem - &v[0];
// any code including continue, break, return
}
Advantages: very compact loop control, direct access to the current element.
Disadvantages: extra statement to get the index. Cannot use different strides.
What to use?
For your particular example of iterating over std::vector
: if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.
For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each
+ a lambda.
Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.
Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.
In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.
The only thing that needs to be done is add width to the <td>
or the <div>
inside the <td>
depending on the layout you want to achieve.
eg:
<table style="width: 100%;" border="1"><tr>
<td><div style="word-wrap: break-word; width: 100px;">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>
or
<table style="width: 100%;" border="1"><tr>
<td width="100" ><div style="word-wrap: break-word; ">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>
After doing what everyone else said above, i.e.:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... my navigation bar was still white. So I added this line:
navigationController?.navigationBar.backgroundColor = .clear
... et voila! That seemed to do the trick.
HTML
create div with id='dvFile'
;
create a button
;
onclick
of that button calling function add_more()
JavaScript
function add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
PHP
if(count($_FILES["item_file"]['name'])>0)
{
//check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
{ //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path))
{
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
//Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //No file upload message
}
In this way you can add file/images, as many as required, and handle them through php script.
The SQL standard way of doing this would be:
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1
Example:
INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;
helloworld
I use the following script:
#!/usr/bin/python
import errno
import os
import sys
toname = dict((str(getattr(errno, x)), x)
for x in dir(errno)
if x.startswith("E"))
tocode = dict((x, getattr(errno, x))
for x in dir(errno)
if x.startswith("E"))
for arg in sys.argv[1:]:
if arg in tocode:
print arg, tocode[arg], os.strerror(tocode[arg])
elif arg in toname:
print toname[arg], arg, os.strerror(int(arg))
else:
print "Unknown:", arg
Just you need to desc with asc. Write the query like below. It will return the values in ascending order.
SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;
For Python = 3.5, use pathlib.Path.mkdir
:
import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
The exist_ok
parameter was added in Python 3.5.
For Python = 3.2, os.makedirs
has an optional third argument exist_ok
that, when True
, enables the mkdir -p
functionality—unless mode
is provided and the existing directory has different permissions than the intended ones; in that case, OSError
is raised as previously:
import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)
For even older versions of Python you can use os.makedirs
and ignore the error:
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python = 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
Have you tried calling TcpClient.Dispose() explicitly?
And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?
The functions.php file doesn't have anything to do with login redirect, what you should be considering it's the wp-login.php file, you can actually change the entire login interface from there, and force users to redirect to your custom pages instead of the /wp-admin/ directory.
Open the file with Notepad if using Windows or any text editor, Prese Ctrl + F (on window) Find "wp-admin/" and change it to the folder you want it to redirect to after login, still on the same file Press Ctrl + F, find "admin_url" and the change the file name, the default file name there is "profile.php"...after just save and give a try.
if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url() ) )
$redirect_to = admin_url('profile.php');
wp_safe_redirect($redirect_to);
exit();
Or you can use the "registration-login plugin" http://wordpress.org/extend/plugins/registration-login/, just simple edit the redirect urls and the links to where you want it to redirect after login, and you've got your very own custom profile.
Old question, but a slightly cleaner approach using LINQ's .Cast<>()
var values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
foreach(var val in values)
{
Console.WriteLine("Member: {0}",val.ToString());
}
I have replaced the printf
calls with calls to warning
in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings()
or any of the other above mentioned methods.
suppressWarnings({ your code })
(Xcode 5 iOS 7) Universal App example for iOS 7 and Xcode 5. It is an open source project / example located here: Link to SimpleWebView (Project Zip and Source Code Example)
ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
content: "\2022";
font-family: FontAwesome;
margin-right: 10px;
display: inline;
vertical-align: middle;
font-size: 1.6em;
font-weight: normal;
}
Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.
Visual for you - http://i.imgur.com/d533SQD.png
The President of the United States employs polymorphism. How? Well, he has many advisers:
Everyone Should only be responsible for one thing: Example:
The president is not an expert in zinc coating, or quantum physics. He doesn't know many things - but he does know only one thing: how to run the country.
It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. Otherwise you'd have the president knowing literally everything in the world - the entire Wikipedia. Imagine having the entire wikipedia in a class of your code: it would be a nightmare to maintain.
Why is that a bad idea for a president to know all these specific things?
If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.
For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.
Is there a better approach?
There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.
He can use a polymorphic approach to running the country.
Example - of using a polymorphic approach:
All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:
public class MisterPresident
{
public void RunTheCountry()
{
// assume the Petraeus and Condi classes etc are instantiated.
petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
condolezza.Advise(); // # she says negotiate trade deal with Iran
healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
}
}
This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".
What you DON"T want:
public class MisterPresident
{
public void RunTheCountry()
{
// people walk into the Presidents office and he tells them what to do
// depending on who they are.
// Fallujah Advice - Mr Prez tells his military exactly what to do.
petraeus.IncreaseTroopNumbers();
petraeus.ImproveSecurity();
petraeus.PayContractors();
// Condi diplomacy advice - Prez tells Condi how to negotiate
condi.StallNegotiations();
condi.LowBallFigure();
condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();
// Health care
healthOfficial.IncreasePremiums();
healthOfficial.AddPreexistingConditions();
}
}
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.
This allows the president to do what he does best: set general policy, look good and play golf :P.
That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)
In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor
interface which just contains one method: Advise()
. But now we are getting into the specifics.
This would be ideal
public class MisterPresident
{
// You can pass in any advisor: Condi, HealthOfficials,
// Petraeus etc. The president has no idea who it will
// be. But he does know that he can ask them to "advise"
// and that's all Mr Prez cares for.
public void RunTheCountry(IAdvisor governmentOfficer)
{
governmentOfficer.Advise();
}
}
public class USA
{
MisterPresident president;
public USA(MisterPresident president)
{
this.president = president;
}
public void ImplementPolicy()
{
IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
president.RunTheCountry(governmentOfficer);
}
}
All that you really need to know is this:
I really hope it helps you. If you don't understand anything post a comment and i'll try again.
You can use the below code on your string and you will get the complete string without html part.
string title = "<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )".Replace(" ",string.Empty);
string s = Regex.Replace(title, "<.*?>", String.Empty);
To get the keys:
function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
let result: string[] = [];
Object.keys(dict).map((key) =>
result.push(key),
);
return result;
}
To accomodate both data scenarios you have, you will want to use this:
datevalue(text(a2,"mm/dd/yyyy"))
That will give you the date number representation for a cell that Excel has in date, or in text datatype.
This will give you DD MM YYYY YY HH Min Sec
variables and works on any Windows machine from XP Pro and later.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Be aware that some browser extensions can add code to the pages. In my case I had an "Emmet in all textareas" plugin that messed up with my requireJs. Make sure that no extra code is beign added to your document by inspecting it in the browser.
if u make this column in sql database (bit) as a data type u should edit this code
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "0";
doWork.TrueValue = "1";
dataGridView1.Columns.Insert(0, doWork);
with this
DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
doWork.HeaderText = "Include Dog";
doWork.FalseValue = "False";
doWork.TrueValue = "True";
dataGridView1.Columns.Insert(0, doWork);
If the goal simply is to list all computer objects with an empty description attribute try this
import-module activedirectory
$domain = "domain.example.com"
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }
safe mode on means (HDFS is in READ only mode)
safe mode off means (HDFS is in Writeable and readable mode)
In Hadoop 2.6.0
, we can check the status of name node with help of the below commands:
TO CHECK THE name node status
$ hdfs dfsadmin -safemode get
TO ENTER IN SAFE MODE:
$ hdfs dfsadmin -safemode enter
TO LEAVE SAFE mode
~$ hdfs dfsadmin -safemode leave
This is because those handlers do not preserve scope. From react documentation: react documentation
Check the "no autobinding" section. You should write the handler like: onClick = () => {}
Your question is based on assumption that the code which may throw NullPointerException
is worse than the code which may not. This assumption is wrong. If you expect that your foobar
is never null due to the program logic, it's much better to use Optional.of(foobar)
as you will see a NullPointerException
which will indicate that your program has a bug. If you use Optional.ofNullable(foobar)
and the foobar
happens to be null
due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.
As described above I executed:
sc delete ServiceName
However this didn't work as I was executing it from PowerShell.
When using PowerShell you must specify the full path to sc.exe
because PowerShell has a default alias for sc
assigning it to Set-Content
. Since it's a valid command it doesn't actually show an error message.
To resolve this I executed it as follows:
C:\Windows\System32\sc.exe delete ServiceName
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
another simplify version
lastBusDay = datetime.datetime.today()
wk_day = datetime.date.weekday(lastBusDay)
if wk_day > 4: #if it's Saturday or Sunday
lastBusDay = lastBusDay - datetime.timedelta(days = wk_day-4) #then make it Friday
By dynamically allocating a Movie object with new Movie()
, you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as
std::vector<Movie *> movies
But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
Actually, RESTfulness only applies to RESOURCES, as indicated by a Universal Resource Identifier. So to even talk about things like headers, cookies, etc. in regards to REST is not really appropriate. REST can work over any protocol, even though it happens to be routinely done over HTTP.
The main determiner is this: if you send a REST call, which is a URI, then once the call makes it successfully to the server, does that URI return the same content, assuming no transitions have been performed (PUT, POST, DELETE)? This test would exclude errors or authentication requests being returned, because in that case, the request has not yet made it to the server, meaning the servlet or application that will return the document corresponding to the given URI.
Likewise, in the case of a POST or PUT, can you send a given URI/payload, and regardless of how many times you send the message, it will always update the same data, so that subsequent GETs will return a consistent result?
REST is about the application data, not about the low-level information required to get that data transferred about.
In the following blog post, Roy Fielding gave a nice summary of the whole REST idea:
http://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/5841
"A RESTful system progresses from one steady-state to the next, and each such steady-state is both a potential start-state and a potential end-state. I.e., a RESTful system is an unknown number of components obeying a simple set of rules such that they are always either at REST or transitioning from one RESTful state to another RESTful state. Each state can be completely understood by the representation(s) it contains and the set of transitions that it provides, with the transitions limited to a uniform set of actions to be understandable. The system may be a complex state diagram, but each user agent is only able to see one state at a time (the current steady-state) and thus each state is simple and can be analyzed independently. A user, OTOH, is able to create their own transitions at any time (e.g., enter a URL, select a bookmark, open an editor, etc.)."
Going to the issue of authentication, whether it is accomplished through cookies or headers, as long as the information isn't part of the URI and POST payload, it really has nothing to do with REST at all. So, in regards to being stateless, we are talking about the application data only.
For example, as the user enters data into a GUI screen, the client is keeping track of what fields have been entered, which have not, any required fields that are missing etc. This is all CLIENT CONTEXT, and should not be sent or tracked by the server. What does get sent to the server is the complete set of fields that need to be modified in the IDENTIFIED resource (by the URI), such that a transition occurs in that resource from one RESTful state to another.
So, the client keeps track of what the user is doing, and only sends logically complete state transitions to the server.
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
For a PRIMARY KEY
, an index will be created with the following message:
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table"
For a FOREIGN KEY
, the constraint will not be created if there is no index on the referenced table.
An index on referencing table is not required (though desired), and therefore will not be implicitly created.
Create a simple hash function and some linked lists of structures , depending on the hash , assign which linked list to insert the value in . Use the hash for retrieving it as well .
I did a simple implementation some time back :
... #define K 16 // chaining coefficient struct dict { char *name; /* name of key */ int val; /* value */ struct dict *next; /* link field */ }; typedef struct dict dict; dict *table[K]; int initialized = 0; void putval ( char *,int); void init_dict() { initialized = 1; int i; for(i=0;iname = (char *) malloc (strlen(key_name)+1); ptr->val = sval; strcpy (ptr->name,key_name); ptr->next = (struct dict *)table[hsh]; table[hsh] = ptr; } int getval ( char *key_name ) { int hsh = hash(key_name); dict *ptr; for (ptr = table[hsh]; ptr != (dict *) 0; ptr = (dict *)ptr->next) if (strcmp (ptr->name,key_name) == 0) return ptr->val; return -1; }
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
go to C:\Windows\System32\drivers\etc and open hosts file and add this
127.0.0.1 example.com
127.0.0.1 www.example.com
then go to C:\xampp\apache\conf\extra open httpd-ajp.conf file and add
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs/pojectroot"
ServerName example.com
ServerAlias www.example.com
<Directory "C:/xampp/htdocs/projectroot">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
I realize this post is old, but there's a more compact approach that is slightly different than what was asked, but may be a very helpful alternative. You can essentially declare the function in-line when calling the method (Foo
's save()
in this case). It would look something like this:
class Foo {
save(callback: (n: number) => any) : void {
callback(42)
}
multipleCallbacks(firstCallback: (s: string) => void, secondCallback: (b: boolean) => boolean): void {
firstCallback("hello world")
let result: boolean = secondCallback(true)
console.log("Resulting boolean: " + result)
}
}
var foo = new Foo()
// Single callback example.
// Just like with @RyanCavanaugh's approach, ensure the parameter(s) and return
// types match the declared types above in the `save()` method definition.
foo.save((newNumber: number) => {
console.log("Some number: " + newNumber)
// This is optional, since "any" is the declared return type.
return newNumber
})
// Multiple callbacks example.
// Each call is on a separate line for clarity.
// Note that `firstCallback()` has a void return type, while the second is boolean.
foo.multipleCallbacks(
(s: string) => {
console.log("Some string: " + s)
},
(b: boolean) => {
console.log("Some boolean: " + b)
let result = b && false
return result
}
)
The multipleCallback()
approach is very useful for things like network calls that may succeed or fail. Again assuming a network call example, when multipleCallbacks()
is called, behavior for both a success and failure can be defined in one spot, which lends itself to greater clarity for future code readers.
Generally, in my experience, this approach lends itself to being more concise, less clutter, and greater clarity overall.
Good luck all!
from functools import reduce
# myiterable can be of any iterable type (including list)
isSorted = reduce(lambda r, e: (r[0] and (r[1] or r[2] <= e), False, e), myiterable, (True, True, None))[0]
The derived reduction value is a 3-part tuple of (sortedSoFarFlag, firstTimeFlag, lastElementValue). It initially starts with (True
, True
, None
), which is also used as the result for an empty list (regarded as sorted because there are no out-of-order elements). As it processes each element it calculates new values for the tuple (using previous tuple values with the next elementValue):
[0] (sortedSoFarFlag) evaluates true if: prev_0 is true and (prev_1 is true or prev_2 <= elementValue)
[1] (firstTimeFlag): False
[2] (lastElementValue): elementValue
The final result of the reduction is a tuple of:
[0]: True/False depending on whether the entire list was in sorted order
[1]: True/False depending on whether the list was empty
[2]: the last element value
The first value is the one we're interested in, so we use [0]
to grab that from the reduce result.
Command line tool that finds Visual Studio solutions and runs the Clean command on them. This lets you clean up the /bin/* directories of all those old projects you have lying around on your harddrive
It has a tricky situation: If you submit a post form, then Chrome will open a new tab to send the request. It's right until now, but if it triggers an event to download file(s), this tab will close immediately so that you cannot capture this request in the Dev Tool.
Solution: Before submitting the post form, you need to cut off your network, which makes the request cannot send successfully so that the tab will not be closed. And then you can capture the request message in the Chrome Devtool(Refreshing the new tab if necessary)
say you have a dict
with tuples as keys, e.g: labels = {(1,2,0): 'label_1'}
you can modify the elements of the tuple keys as follows:
formatted_labels = {(elem[0],elem[1]):labels[elem] for elem in labels}
Here, we ignore the last elements.
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
My framework was working before and suddenly stopped working, and none of these answers were working for me. I removed the framework in Build Phases > Link Binary With Libraries, and re-added it. Started working again.
try using the Date
property on the DateTime
Object...
if(dtOne.Date == dtTwo.Date)
....
This seems to work fine for intel Mac 10.7:
#include <time.h>
time_t start = time(NULL);
//Do your work
time_t end = time(NULL);
std::cout<<"Execution Time: "<< (double)(end-start)<<" Seconds"<<std::endl;
To store actual Unicode codepoints, you have to first decode the String's UTF-16 codeunits to UTF-32 codeunits (which are currently the same as the Unicode codepoints). Use System.Text.Encoding.UTF32.GetBytes()
for that, and then write the resulting bytes to the StringBuilder
as needed,i.e.
static void Main(string[] args)
{
String originalString = "This string contains the unicode character Pi(p)";
Byte[] bytes = Encoding.UTF32.GetBytes(originalString);
StringBuilder asAscii = new StringBuilder();
for (int idx = 0; idx < bytes.Length; idx += 4)
{
uint codepoint = BitConverter.ToUInt32(bytes, idx);
if (codepoint <= 127)
asAscii.Append(Convert.ToChar(codepoint));
else
asAscii.AppendFormat("\\u{0:x4}", codepoint);
}
Console.WriteLine("Final string: {0}", asAscii);
Console.ReadKey();
}
Window
is the main JavaScript object root, aka the global object
in a browser, also can be treated as the root of the document object model. You can access it as window
window.screen
or just screen
is a small information object about physical screen dimensions.
window.document
or just document
is the main object of the potentially visible (or better yet: rendered) document object model/DOM.
Since window
is the global object you can reference any properties of it with just the property name - so you do not have to write down window.
- it will be figured out by the runtime.
This is a project for getting IP address of any website , it's usefull and so easy to make.
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}
in data.frame it is not necessary to create a new column by mutate.
library(tidyverse)
k <- c(1,2,80,NA,NA,51)
j <- c(NA,NA,3,31,12,NA)
df <- data.frame(k,j)%>%
replace_na(list(j=0))#convert only column j, for example
result
k j
1 0
2 0
80 3
NA 31
NA 12
51 0
Have you set AcceptsReturn property to true?
If you want to maintain your scroll position when you refresh, and you can do this:
if (mEventListView.getAdapter() == null) {
EventLogAdapter eventLogAdapter = new EventLogAdapter(mContext, events);
mEventListView.setAdapter(eventLogAdapter);
} else {
((EventLogAdapter)mEventListView.getAdapter()).refill(events);
}
public void refill(List<EventLog> events) {
mEvents.clear();
mEvents.addAll(events);
notifyDataSetChanged();
}
For the detail information, please see Android ListView: Maintain your scroll position when you refresh.
A general answer involves using a Manager
object. Adapted from the docs:
from multiprocessing import Process, Manager
def f(d):
d[1] += '1'
d['2'] += 2
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
d[1] = '1'
d['2'] = 2
p1 = Process(target=f, args=(d,))
p2 = Process(target=f, args=(d,))
p1.start()
p2.start()
p1.join()
p2.join()
print d
Output:
$ python mul.py
{1: '111', '2': 6}
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
var url = window.location.origin + window.location.pathname;
You can try this way
String input = "";
try {
int x = Integer.parseInt(input);
// You can use this method to convert String to int, But if input
//is not an int value then this will throws NumberFormatException.
System.out.println("Valid input");
}catch(NumberFormatException e) {
System.out.println("input is not an int value");
// Here catch NumberFormatException
// So input is not a int.
}
You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.
You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).
So, you open the device using open() and get a file descriptor, then use it in tcgetattr()
to fill your termios structure.
Then clear CBAUD
and set CBAUDEX
on c_cflag
.
CBAUDEX
has the same value as BOTHER.
After setting this, you can set a custom baud rate using normal functions, like cfsetspeed()
, specifying the desired baud rate as an integer.
IntVar = int("".join(filter(str.isdigit, StringVar)))
To cover Unicode whitespace characters:
set list
set listchars=tab:¦\ ,nbsp:·
highlight StrangeWhitespace guibg=Red ctermbg=Red
" The list is from https://stackoverflow.com/a/37903645 (with `\t`, `\n`, ` `, `\xa0` removed):
call matchadd('StrangeWhitespace', '[\x0b\x0c\r\x1c\x1d\x1e\x1f\x85\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]')
The result:
")¦
" (two characters: a long pipe and then an ordinal space; they are gray in colorscheme murphy
)·
" (one character; it's gray in colorscheme murphy
)
"DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.
I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.
For react-router 1, 2 and 3
If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)
<Route path='*' exact={true} component={My404Component} />
If you want to display a 404 page but change the url (Same functionality as DefaultRoute)
<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />
Example with multiple levels:
<Route path='/' component={Layout} />
<IndexRoute component={MyComponent} />
<Route path='/users' component={MyComponent}>
<Route path='user/:id' component={MyComponent} />
<Route path='*' component={UsersNotFound} />
</Route>
<Route path='/settings' component={MyComponent} />
<Route path='*' exact={true} component={GenericNotFound} />
</Route>
For react-router 4 and 5
Keep the path
<Switch>
<Route exact path="/users" component={MyComponent} />
<Route component={GenericNotFound} />
</Switch>
Redirect to another route (change url)
<Switch>
<Route path="/users" component={MyComponent} />
<Route path="/404" component={GenericNotFound} />
<Redirect to="/404" />
</Switch>
The order matters!
Try this another way:
var qry = Employees
.OrderByDescending (s => s.EmpFName)
.ThenBy (s => s.Address)
.Select (s => s.EmpCode);
A few resources:
Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.
The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.
So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...
I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.
The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.
The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.
I hope the idea helps you out.
I've had the same problem.
Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.
In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :
<script>document.write('<style>.js_hidden { display: none; }</style>');</script>
<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>
Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :
This'll work:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function myFunc(id)
{
alert(id);
}
</script>
</head>
<body>
<button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
<button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
<button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
<button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
</body>
</html>
Check your npm
version
If it's not properly installed, then install it first
run this command npm install typescript -g
now tsc <file_name>.ts
It'll create a corresponding .js
file. eg <file_name>.js
now try node <file_name>.js
Is m_cRedundencyManager
able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.
Update: The function declaration you provided shows that m_cRedundencyManager
is expecting a function of the form: void yourCallbackFunction(int, void *)
. Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *
.
// in your CLoggersInfra constructor:
m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);
// in your CLoggersInfra header:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);
// in your CLoggersInfra source file:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
{
((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
}
First of all you should configure $resource
in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions)
. It is also to be mentioned that you configure get
method of resource and using query
instead.
Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource(
'../rest/api.php',
{ method: 'getTask', q: '*' }, // Query parameters
{'query': { method: 'GET' }}
);
})
Documentation
Can you try the following?
psexec \\server cmd /c "echo . | powershell script.ps1"
In an application level, here are something a developer can do:
From server side:
Check if load balancer(if you have),works correctly.
Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.
Eg: If you are using node server, u can use toobusy from npm. Implementation something like:
var toobusy = require('toobusy');
app.use(function(req, res, next) {
if (toobusy()) res.send(503, "I'm busy right now, sorry.");
else next();
});
Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html
We can do some work in client side too:
Try to group calls in batch, reduce the traffic and total requests number b/w client and server.
Try to build a cache mid-layer to handle unnecessary duplicates requests.
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
This is for extra information.
Imagine this scenario
ActivityB launch a new ActivityAPrime by
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
ActivityAPrime has no relationship with ActivityA.
In this case the Bundle in ActivityAPrime.onCreate() will be null.
If ActivityA and ActivityAPrime should be the same activity instead of different activities, ActivityB should call finish() than using startActivity().
I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line
; On windows: extension_dir = "ext"
I changed it to:
; On windows: extension_dir = "C:\php\ext"
And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.
This two commands work for me in my project
composer require laravel/ui --dev
Then
php artisan ui:auth
For those who want that their editText should accept only alphabets and space (neither numerics nor any special characters), then one can use this InputFilter
.
Here I have created a method named getEditTextFilter()
and written the InputFilter inside it.
public static InputFilter getEditTextFilter() {
return new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
private boolean isCharAllowed(char c) {
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(String.valueOf(c));
return ms.matches();
}
};
}
Attach this inputFilter to your editText after finding it, like this :
mEditText.setFilters(new InputFilter[]{getEditTextFilter()});
The original credit goes to @UMAR who gave the idea of validating using regular expression and @KamilSeweryn
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
ToggleImageButton
which implements Checkable
interface and supports OnCheckedChangeListener
and android:checked
xml attribute:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )
The plt.subplots_adjust method:
def subplots_adjust(*args, **kwargs):
"""
call signature::
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
Tune the subplot layout via the
:class:`matplotlib.figure.SubplotParams` mechanism. The parameter
meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
fig = gcf()
fig.subplots_adjust(*args, **kwargs)
draw_if_interactive()
or
fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )
The size of the picture matters.
"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."
Thus to make more white space and keep the sub plot size the total image needs to be bigger.
Try this solution. It works fine.
try{
String url = textBox1.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(sr);
var aTags = doc.DocumentNode.SelectNodes("//a");
int counter = 1;
if (aTags != null)
{
foreach (var aTag in aTags)
{
richTextBox1.Text += aTag.InnerHtml + "\n" ;
counter++;
}
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Failed to retrieve related keywords." + ex);
}
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
The following code is working fine. Run the code snippet what it does.
Maybe it can be cleaned up or make it automatically work with all text tags in SVG.
function svg_textMultiline() {_x000D_
_x000D_
var x = 0;_x000D_
var y = 20;_x000D_
var width = 360;_x000D_
var lineHeight = 10;_x000D_
_x000D_
_x000D_
_x000D_
/* get the text */_x000D_
var element = document.getElementById('test');_x000D_
var text = element.innerHTML;_x000D_
_x000D_
/* split the words into array */_x000D_
var words = text.split(' ');_x000D_
var line = '';_x000D_
_x000D_
/* Make a tspan for testing */_x000D_
element.innerHTML = '<tspan id="PROCESSING">busy</tspan >';_x000D_
_x000D_
for (var n = 0; n < words.length; n++) {_x000D_
var testLine = line + words[n] + ' ';_x000D_
var testElem = document.getElementById('PROCESSING');_x000D_
/* Add line in testElement */_x000D_
testElem.innerHTML = testLine;_x000D_
/* Messure textElement */_x000D_
var metrics = testElem.getBoundingClientRect();_x000D_
testWidth = metrics.width;_x000D_
_x000D_
if (testWidth > width && n > 0) {_x000D_
element.innerHTML += '<tspan x="0" dy="' + y + '">' + line + '</tspan>';_x000D_
line = words[n] + ' ';_x000D_
} else {_x000D_
line = testLine;_x000D_
}_x000D_
}_x000D_
_x000D_
element.innerHTML += '<tspan x="0" dy="' + y + '">' + line + '</tspan>';_x000D_
document.getElementById("PROCESSING").remove();_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
svg_textMultiline();
_x000D_
body {_x000D_
font-family: arial;_x000D_
font-size: 20px;_x000D_
}_x000D_
svg {_x000D_
background: #dfdfdf;_x000D_
border:1px solid #aaa;_x000D_
}_x000D_
svg text {_x000D_
fill: blue;_x000D_
stroke: red;_x000D_
stroke-width: 0.3;_x000D_
stroke-linejoin: round;_x000D_
stroke-linecap: round;_x000D_
}
_x000D_
<svg height="300" width="500" xmlns="http://www.w3.org/2000/svg" version="1.1">_x000D_
_x000D_
<text id="test" y="0">GIETEN - Het college van Aa en Hunze is in de fout gegaan met het weigeren van een zorgproject in het failliete hotel Braams in Gieten. Dat stelt de PvdA-fractie in een brief aan het college. De partij wil opheldering over de kwestie en heeft schriftelijke_x000D_
vragen ingediend. Verkeerde route De PvdA vindt dat de gemeenteraad eerst gepolst had moeten worden, voordat het college het plan afwees. "Volgens ons is de verkeerde route gekozen", zegt PvdA-raadslid Henk Santes.</text>_x000D_
_x000D_
</svg>
_x000D_
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
If you are using IntelliJ IDE just right click on resources package and go to new and then select Resource Boundle it automatically create a .properties file for you. This did work for me .
String str = "Your string";
byte[] array = str.getBytes();
You can take a look at my splash screen implementation: C# winforms startup (Splash) form not hiding
Easy:
<%= link_to image_tag("Search.png", :border=>0), :action => 'search', :controller => 'pages', :class => 'dock-item' %>
The first param of link_to is the text/html to link (inside the a tag). The next set of parameters is the url properties and the link attributes themselves.
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
One should always replace like this:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/
it declares that the type is nullable.
I had to use Stylesheet directory to work for me.
<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">
window.open(skey, "_blank", "toolbar=1, scrollbars=1, resizable=1, width=" + 1015 + ", height=" + 800);
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.
This usually occurs because either of the following are true:
Try getting some information about the certificate of the server and see if you need to install any specific certs on your client to get it to work.
This worked well for me.
curl -X POST --data @json_out.txt http://localhost:8080/
Where,
-X
Means the http verb.
--data
Means the data you want to send.
I believe the solution by @slipset was correct, but wasn't cross-browser ready.
According to Javascript.info, events (when referenced outside markup events) are cross-browser ready once you assure it's defined with this simple line: event = event || window.event
.
So the complete cross-browser ready function would look like this:
function doSomething(param){
event = event || window.event;
var source = event.target || event.srcElement;
console.log(source);
}
<ul>
<li class="span4">One <input class="btn btn-small" value="test"></li>
<li class="span4">Two <input class="btn btn-small" value="test2"></li>
</ul>
One way would be to apply this style to your list items in order to keep them inline
or
<ul>
<li>One <input class="btn" value="test"></li>
<li>Two <input class="btn" value="test2"></li>
</ul>
in CSS
li {
line-height: 20px;
margin: 5px;
padding: 2px;
}
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
Some of the answers involve creating a new public
method. Without doing this, use the Lazy<T>
class:
public class ViewModel
{
private Lazy<ObservableCollection<TData>> Data;
async public ViewModel()
{
Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
}
public ObservableCollection<TData> GetDataTask()
{
Task<ObservableCollection<TData>> task;
//Create a task which represents getting the data
return task.GetAwaiter().GetResult();
}
}
To use Data
, use Data.Value
.
Try this,
$('.nav-list li').click(function() {
$('.nav-list li.active').removeClass('active');
$(this).addClass('active');
});
In your context $(this)
will points to the UL
element not the Li
. Hence you are not getting the expected results.
Using dispose();
is a very effective way for closing your programs.
I found that using System.exit(x)
resets the interactions pane and supposing you need some of the information there it all disappears.
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
Here goes:
DECLARE @var nvarchar(max) = 'Man''s best friend';
You will note that the '
is escaped by doubling it to ''
.
Since the string delimiter is '
and not "
, there is no need to escape "
:
DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';
The second example in the MSDN page on DECLARE
shows the correct syntax.
Holding shift while copying and pasting with selection worked for me
varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.
UPDATE FOR VS CODE 1.40.0
After doing:
$ pip install pylint-django
Follow this link: https://code.visualstudio.com/docs/python/linting#_default-pylint-rules
Notice that the way to make pylint
have into account pylint-django
is by specifying:
"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
in the settings.json
of VS Code.
But after that, you will notice a lot of new linting errors. Then, read what it said here:
These arguments are passed whenever the
python.linting.pylintUseMinimalCheckers
is set totrue
(the default). If you specify a value inpylintArgs
or use a Pylint configuration file (see the next section), thenpylintUseMinimalCheckers
is implicitly set to false.
What I have done is creating a .pylintrc
file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):
load-plugins=pylint_django
disable=all
enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode
Now pylint
works as expected.
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose
.feature_desc {
display: block;
}
.feature_desc:before {
content: "";
display: block;
}
might give you want you want to achieve without the <br/>
element. Though it would help to see your CSS applied to these elements.
NOTE. The example above doesn't work in IE7 though.
I would like to post rather a Designer approach to this, this will keep design separate from your business logic:
Step 1. Create new style in (res->values->styles.xml) : Basically it is copy of your overall scheme with different parent - parent="Theme.AppCompat.Light.NoActionBar"
<!-- custom application theme. -->
<style name="MarkitTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimary</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
</style>
Step 2: In your AndroidManifest.xml, add this theme to the activity you want in: e.g. I want my main activity without action-bar so add this like below:
<activity android:name=".MainActivity"
android:theme="@style/MarkitTheme">
This is the best solution for me after trying a lot of things.
I didn't want to delete all the packages in vendor/
directory, so here is how I did it:
rm -rf vendor/package-i-messed-up
composer install
againThis seems to have changed (probably with log4j2) to:
-Dlog4j.configurationFile=file:C:\Users\me\log4j.xml
See: https://logging.apache.org/log4j/2.x/manual/configuration.html
In my case this error came up when the Sub name was identical to the Module name.
Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str
representation of its args
), which may be useful.
from unittest import TestCase
class TestNoneTypeError(TestCase):
def setUp(self):
self.testListNone = None
def testListSlicing(self):
with self.assertRaises(TypeError) as ctx:
self.testListNone[:1]
self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))
If the project is maven placed it in src/main/resources
, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml
Try adding
to the empty items.
I don't understand why you're not using a <table>
here, though? They will do this kind of stuff automatically.
Here is my submission!
if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.
The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.
The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.
// Server_x000D_
var io1 = require('socket.io').listen(8321);_x000D_
_x000D_
io1.on('connection', function(socket1) {_x000D_
socket1.on('bar', function(msg1) {_x000D_
console.log(msg1);_x000D_
});_x000D_
});_x000D_
_x000D_
// Mirror_x000D_
var ioIn = require('socket.io').listen(8123);_x000D_
var ioOut = require('socket.io-client');_x000D_
var socketOut = ioOut.connect('http://localhost:8321');_x000D_
_x000D_
_x000D_
ioIn.on('connection', function(socketIn) {_x000D_
socketIn.on('foo', function(msg) {_x000D_
socketOut.emit('bar', msg);_x000D_
});_x000D_
});_x000D_
_x000D_
// Client_x000D_
var io2 = require('socket.io-client');_x000D_
var socket2 = io2.connect('http://localhost:8123');_x000D_
_x000D_
var msg2 = "hello";_x000D_
socket2.emit('foo', msg2);
_x000D_
Add one more condition in where clause
SELECT * FROM product
WHERE pdate >= DATEADD(day,-30,GETDATE())
and pdate <= getdate()
Or use DateDiff
SELECT * FROM product
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30
I've created a directive for AngularJS - heavely inspired by GeekyMonkey's answer but without the jQuery dependency.
Demo: http://plnkr.co/edit/8tPCZIjvO3VSApSeTtYr?p=preview
Markup
<div class="fittext" max-font-size="50" text="Your text goes here..."></div>
Directive
app.directive('fittext', function() {
return {
scope: {
minFontSize: '@',
maxFontSize: '@',
text: '='
},
restrict: 'C',
transclude: true,
template: '<div ng-transclude class="textContainer" ng-bind="text"></div>',
controller: function($scope, $element, $attrs) {
var fontSize = $scope.maxFontSize || 50;
var minFontSize = $scope.minFontSize || 8;
// text container
var textContainer = $element[0].querySelector('.textContainer');
angular.element(textContainer).css('word-wrap', 'break-word');
// max dimensions for text container
var maxHeight = $element[0].offsetHeight;
var maxWidth = $element[0].offsetWidth;
var textContainerHeight;
var textContainerWidth;
var resizeText = function(){
do {
// set new font size and determine resulting dimensions
textContainer.style.fontSize = fontSize + 'px';
textContainerHeight = textContainer.offsetHeight;
textContainerWidth = textContainer.offsetWidth;
// shrink font size
var ratioHeight = Math.floor(textContainerHeight / maxHeight);
var ratioWidth = Math.floor(textContainerWidth / maxWidth);
var shrinkFactor = ratioHeight > ratioWidth ? ratioHeight : ratioWidth;
fontSize -= shrinkFactor;
} while ((textContainerHeight > maxHeight || textContainerWidth > maxWidth) && fontSize > minFontSize);
};
// watch for changes to text
$scope.$watch('text', function(newText, oldText){
if(newText === undefined) return;
// text was deleted
if(oldText !== undefined && newText.length < oldText.length){
fontSize = $scope.maxFontSize;
}
resizeText();
});
}
};
});