Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
in VS 2017 I cleaned the solution and rebuilt it and that fixed it
In my case i have changed the root folder in which the Eclipse project were stored. I have discovered tha when i have runned :
cat .plugins/org.eclip.resources/.projects/<projectname>/.location
Here's a super short template to do the sorting right away :
Collections.sort(people,new Comparator<Person>(){
@Override
public int compare(final Person lhs,Person rhs) {
//TODO return 1 if rhs should be before lhs
// return -1 if lhs should be before rhs
// return 0 otherwise (meaning the order stays the same)
}
});
if it's hard to remember, try to just remember that it's similar (in terms of the sign of the number) to:
lhs-rhs
That's in case you want to sort in ascending order : from smallest number to largest number.
Here's the list of logger categories:
Category Function
org.hibernate.SQL Log all SQL DML statements as they are executed
org.hibernate.type Log all JDBC parameters
org.hibernate.tool.hbm2ddl Log all SQL DDL statements as they are executed
org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache Log all second-level cache activity
org.hibernate.transaction Log transaction related activity
org.hibernate.jdbc Log all JDBC resource acquisition
org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing
org.hibernate.secure Log all JAAS authorization requests
org.hibernate Log everything (a lot of information, but very useful for troubleshooting)
Formatted for pasting into a log4j XML configuration file:
<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />
NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.
And a category is specified as such:
<logger name="org.hibernate">
<level value="ALL" />
<appender-ref ref="FILE"/>
</logger>
It must be placed before the root element.
There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:
http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp
Preferences -> Remote Systems -> Files -> Show hidden files
(make sure this is checked)
I found easiest solution.
@XmlElement(name="attribute")
public String[] getAttributes(){
return attributes.keySet().toArray(new String[1]);
}
}
Now it will generate in you xml output like this:
<attribute>key1<attribute>
...
<attribute>keyN<attribute>
AddressSanitizer (ASan) is a fast memory error detector. It finds use-after-free and {heap,stack,global}-buffer overflow bugs in C/C++ programs. It finds:
This tool is very fast. The average slowdown of the instrumented program is ~2x.
You seem to be passing the From
address as emailAddress
, which is not a proper email address. For Office365 the From
needs to be a real address on the Office365 system.
You can validate that if you hardcode your email address as the From
and your Office 365 password.
Don't leave it there though of course.
DataSet myDataset = new DataSet();
DataTable customers = myDataset.Tables.Add("Customers");
customers.Columns.Add("Name");
customers.Columns.Add("Age");
customers.Rows.Add("Chris", "25");
//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
currentRow = myCustomers.Rows[i];
listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));
}
for this find the given Object in an Array, a basic usage example of _.find
const array =
[
{
description: 'object1', id: 1
},
{
description: 'object2', id: 2
},
{
description: 'object3', id: 3
},
{
description: 'object4', id: 4
}
];
this would work well
q = _.find(array, {id:'4'}); // delete id
console.log(q); // {description: 'object4', id: 4}
_.find will help with returning an element in an array, rather than it’s index. So if you have an array of objects and you want to find a single object in the array by a certain key value pare _.find is the right tools for the job.
I am doing this
Collection.All(c => { c.needsChange = value; return true; });
I don't think you can. What you can do, however, is create different profiles for each proxy setting, and use the following command to switch between profiles when running Firefox:
firefox -no-remote -P <profilename>
Currently the Array.forEach prototype property doesn't support async operations, but we can create our own poly-fill to meet our needs.
// Example of asyncForEach Array poly-fill for NodeJs
// file: asyncForEach.js
// Define asynForEach function
async function asyncForEach(iteratorFunction){
let indexer = 0
for(let data of this){
await iteratorFunction(data, indexer)
indexer++
}
}
// Append it as an Array prototype property
Array.prototype.asyncForEach = asyncForEach
module.exports = {Array}
And that's it! You now have an async forEach method available on any arrays that are defined after these to operations.
Let's test it...
// Nodejs style
// file: someOtherFile.js
const readline = require('readline')
Array = require('./asyncForEach').Array
const log = console.log
// Create a stream interface
function createReader(options={prompt: '>'}){
return readline.createInterface({
input: process.stdin
,output: process.stdout
,prompt: options.prompt !== undefined ? options.prompt : '>'
})
}
// Create a cli stream reader
async function getUserIn(question, options={prompt:'>'}){
log(question)
let reader = createReader(options)
return new Promise((res)=>{
reader.on('line', (answer)=>{
process.stdout.cursorTo(0, 0)
process.stdout.clearScreenDown()
reader.close()
res(answer)
})
})
}
let questions = [
`What's your name`
,`What's your favorite programming language`
,`What's your favorite async function`
]
let responses = {}
async function getResponses(){
// Notice we have to prepend await before calling the async Array function
// in order for it to function as expected
await questions.asyncForEach(async function(question, index){
let answer = await getUserIn(question)
responses[question] = answer
})
}
async function main(){
await getResponses()
log(responses)
}
main()
// Should prompt user for an answer to each question and then
// log each question and answer as an object to the terminal
We could do the same for some of the other array functions like map...
async function asyncMap(iteratorFunction){
let newMap = []
let indexer = 0
for(let data of this){
newMap[indexer] = await iteratorFunction(data, indexer, this)
indexer++
}
return newMap
}
Array.prototype.asyncMap = asyncMap
... and so on :)
Some things to note:
Array.prototype.<yourAsyncFunc> = <yourAsyncFunc>
will not have this feature availableJust a clarification on the answer given by Bkkbrad.
I tried this suggestion and it did not work for me.
For example,
split('aa|bb','\\|')
produced:
["","a","a","|","b","b",""]
But,
split('aa|bb','[|]')
produced the desired result:
["aa","bb"]
Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.
For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html
This may work as well.
SELECT *
FROM myTable
WHERE CHARINDEX('mall', name) > 0
OR CHARINDEX('mall', description) > 0
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
If you have only one char and not a string, you can use:
'\n'.charCodeAt();
omitting the 0...
It used to be significantly slower than 'n'.charCodeAt(0)
, but I've tested it now and I do not see any difference anymore (executed 10 billions times with and without the 0). Tested for performance only in Chrome and Firefox.
How about this?
<ul>
<?php while ($items = array_pop($lists)) { ?>
<ul>
<?php foreach ($items as $item) { ?>
<li><?= $item ?></li>
<?php
}//foreach
}//while ?>
We can still use the more widely-used braces and, at the same time, increase readability.
I believe a const
value is the same for all objects (and must be initialized with a literal expression), whereas readonly
can be different for each instantiation...
The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.
Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.
ASP.NET 2 and SQL Server reporting services 2005 have a limit of 2028. I found this out the hard way, where my dynamic URL generator would not pass over some parameters to a report beyond that point. This was under Internet Explorer 8.
git reset HEAD~1
if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]
I've tested all suggested methods plus np.array(map(f, x))
with perfplot
(a small project of mine).
Message #1: If you can use numpy's native functions, do that.
If the function you're trying to vectorize already is vectorized (like the x**2
example in the original post), using that is much faster than anything else (note the log scale):
If you actually need vectorization, it doesn't really matter much which variant you use.
Code to reproduce the plots:
import numpy as np
import perfplot
import math
def f(x):
# return math.sqrt(x)
return np.sqrt(x)
vf = np.vectorize(f)
def array_for(x):
return np.array([f(xi) for xi in x])
def array_map(x):
return np.array(list(map(f, x)))
def fromiter(x):
return np.fromiter((f(xi) for xi in x), x.dtype)
def vectorize(x):
return np.vectorize(f)(x)
def vectorize_without_init(x):
return vf(x)
perfplot.show(
setup=np.random.rand,
n_range=[2 ** k for k in range(20)],
kernels=[f, array_for, array_map, fromiter, vectorize, vectorize_without_init],
xlabel="len(x)",
)
You might consider using a shell without history, like perhaps
/bin/sh << END
your commands without history
END
(perhaps /bin/dash
or /bin/sash
could be more appropriate than /bin/sh
)
or even better use the batch utility e.g
batch << EOB
your commands
EOB
The history would then contain sh
or batch
which is not very meaningful
Assume a dataframe with 19 rows
index=range(0,19)
index
columns=['A']
test = pd.DataFrame(index=index, columns=columns)
Keeping Column A as a constant
test['A']=10
Keeping column b as a variable given by a loop
for x in range(0,19):
test.loc[[x], 'b'] = pd.Series([x], index = [x])
You can replace the first x in pd.Series([x], index = [x])
with any value
The following method avoids manually messing with the /usr/lib
directory while also requiring minimal change in your CMakeLists.txt
file. It also lets your package manager cleanly uninstall libgtest-dev
.
The idea is that when you get the libgtest-dev
package via
sudo apt install libgtest-dev
The source is stored in location /usr/src/googletest
You can simply point your CMakeLists.txt
to that directory so that it can find the necessary dependencies
Simply replace FindGTest
with add_subdirectory(/usr/src/googletest gtest)
At the end, it should look like this
add_subdirectory(/usr/src/googletest gtest)
target_link_libraries(your_executable gtest)
In the answer that uses the registry, I found that on Windows 2008 R2 SP1, you need to drop the Background out of the path. Further, since the chere and xhere are not part of cygwin64, here is a solution that works for both, combining the registry and the Send To solutions. Replace 'E:\cygwin64' with your install location:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash]
@="Open Cygwin Here"
[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash\command]
@="E:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico --exec /bin/bash.exe --login -c \"cd '%1' ; exec bash -rcfile ~/.bashrc\""
Ctrl++
or
Ctrl+=
Ctrl+-
This feature is described here:
In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.
So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.
First, get the string that identifies the commit in some date, doing:
git rev-list -n 1 --before="2009-07-27 13:37" origin/master
It prints the commit identifier, takes the string (for instance XXXX) and does:
git checkout XXXX
Another way of doing this is using Uri.EscapeUriString(stringToEscape)
.
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
nchar(10) is a fixed-length Unicode string of length 10. nvarchar(10) is a variable-length Unicode string with a maximum length of 10. Typically, you would use the former if all data values are 10 characters and the latter if the lengths vary.
Run it every three days...
0 0 */3 * *
How about that?
If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.
if (((date('j') - 1) % 3))
exit();
or, as @mario points out, you can use date('k') to get the day of the year instead of doing it based on the day of the month.
Its just because of the load time angular takes to give you the current state.
If you try to get the current state by using $timeout
function then it will give you correct result in $state.current.name
$timeout(function(){
$rootScope.currState = $state.current.name;
})
First, I strongly recommend that you rename your variable list
to something else. list
is the name of the built-in list constructor, and you're hiding its normal function. I will rename list
to a
in the following.
Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a
it's referring to the same actual list object as last time. So when you call
listoflists.append((a, a[0]))
you can later change a
and it changes what the first element of that tuple points to. This does not happen with a[0]
because the object (which is an integer) pointed to by a[0]
doesn't change (although a[0]
points to different objects over the run of your code).
You can create a copy of the whole list a
using the list
constructor:
listoflists.append((list(a), a[0]))
Or, you can use the slice notation to make a copy:
listoflists.append((a[:], a[0]))
All cookies expire as per the cookie specification, so this is not a PHP limitation.
Use a far future date. For example, set a cookie that expires in ten years:
setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.
Python's built-in float
type has double precision (it's a C double
in CPython, a Java double
in Jython). If you need more precision, get NumPy and use its numpy.float128
.
While the rules in C++03 about when you need typename
and template
are largely reasonable, there is one annoying disadvantage of its formulation
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type
can only be int
(and is hence a type), and this->g
can only be the member template g
declared later (even if A
is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A
!).
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A
, A<T>
, ::A<T>
). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass
and A
are both current instantiations).
Based on this notion, the language says that CurrentInstantiation::Foo
, Foo
and CurrentInstantiationTyped->Foo
(such as A *a = this; a->Foo
) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords typename
and template
are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T>
is still a type-dependent name (after all T
is also type dependent). But A<T>::result_type
is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type
when instantiating D::f
(even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C
like this
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
A compiler is required to catch the error when instantiating D<int>::f
. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename
and template
.
In the code of D
, the name typename D::questionable_type
is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo
or DependentTypedName->Foo
and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo
is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function h
within the above defined A
class template
void h() {
typename A<T>::questionable_type x;
}
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h
(whatever argument you give to T
). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A
has no dependent base classes, and A
declares no member questionable_type
, the name A<T>::questionable_type
is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
This valid C++03 code would bind this->f
to A::f
at instantiation time and everything is fine. C++11 however immediately binds it to B::f
and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g
, the Dominance Rule applies and lookup will find A::f
instead.
Use the a
mode. It stands for append
.
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
fclose($myfile);
The error message says
"The path to the driver executable must be set by the webdriver.ie.driver system property;"
You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.
You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value
-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe"
You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.
You could also use
System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe");
inside your code.
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
First go to the directory where your python script is present by using-
cd path/to/directory
then simply do:
python file_name.py
I have the same problem and so I remove the Apache and make it again and the problem was solved.
# This script fragment emits Cygwin rulez under bash/cygwin
if [[ $(uname -s) == CYGWIN* ]];then
echo Cygwin rulez
else
echo Unix is king
fi
If the 6 first chars of uname -s command is "CYGWIN", a cygwin system is assumed
You can go without the loop:
find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \;
HTH
The best way to create internal links (related with sections) is create list but instead of link, put #section
or #section-title
if the header includes spaces.
Markdown
Go to section
* [Hello](#hello)
* [Hello World](#hello-world)
* [Another section](#new-section) <-- it's called 'Another section' in this list but refers to 'New section'
## Hello
### Hello World
## New section
List preview
Go to section
Hello <-- [Hello](#hello) -- go to `Hello` section
Hello World <-- [Hello World](#hello world) -- go to `Hello World` section
Another section <-- [Another section](#new-section) -- go to `New section`
HTML
<p>Go to section</p>
<ul>
<li><a href="#hello">Hello</a></li>
<li><a href="#hello-world">Hello World</a></li>
<li><a href="#new-section">Another section</a> <– it’s called ‘Another section’ in this list but refers to ‘New section’</li>
</ul>
<h2 id="hello">Hello</h2>
<h3 id="hello-world">Hello World</h3>
<h2 id="new-section">New section</h2>
It doesn't matter whether it's h1
, h2
, h3
, etc. header, you always refer to it using just one #
.
All references in section list should be converted to lowercase text as it is shown in the example above.
The link to the section should be lowercase. It won't work otherwise. This technique works very well for all Markdown variants, also MultiMarkdown.
Currently I'm using the Pandoc to convert documents format. It's much better than MultiMarkdown.
Test Pandoc here
Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.
I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.
I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.
The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid
and I didn't..
Yes the workaround shown in all answer is correct , that is we need to customize the linear layout manager to calculate the height of its child items dynamically at run time. But all answers not working as expected .Please the below answer for custom layout manger with all orientation support.
public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private final RecyclerView view;
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
super(context);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
super(view.getContext());
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
super(view.getContext(), orientation, reverseLayout);
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
public void setOverScrollMode(int overScrollMode) {
if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
if (this.view == null) throw new IllegalStateException("view == null");
this.overScrollMode = overScrollMode;
ViewCompat.setOverScrollMode(view, overScrollMode);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSize, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (hasHeightSize && height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSize, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (hasWidthSize && width >= widthSize) {
break;
}
}
}
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
if (hasWidthSize) {
width = Math.min(width, widthSize);
}
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
if (hasHeightSize) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
final View child;
try {
child = recycler.getViewForPosition(position);
} catch (IndexOutOfBoundsException e) {
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
return;
}
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
makeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
calculateItemDecorationsForChild(child, tmpRect);
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
// as view is recycled let's not keep old measured values
makeInsetsDirty(p);
recycler.recycleView(child);
}
private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
if (!canMakeInsetsDirty) {
return;
}
try {
if (insetsDirtyField == null) {
insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
insetsDirtyField.setAccessible(true);
}
insetsDirtyField.set(p, true);
} catch (NoSuchFieldException e) {
onMakeInsertDirtyFailed();
} catch (IllegalAccessException e) {
onMakeInsertDirtyFailed();
}
}
private static void onMakeInsertDirtyFailed() {
canMakeInsetsDirty = false;
if (BuildConfig.DEBUG) {
Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
}
}
}
In my case, the solution was to change not only config.ini
but also hardware.ini
for the specific skin from hw.ramSize=1024
to hw.ramSize=1024MB
.
To find the hardware.ini
file:
config.ini
and locate skin.path
.android-sdk\platforms\android-15\skins\WXGA720
.hardware.ini
.hw.ramSize=1024
to hw.ramSize=1024MB
.You would never want to run that, but you may want to source it.
. ~/.bash_profile
source ~/.bash_profile
both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
it's not that complicated.
please try this:
$(document).ready(function(){
var modalId = "#myModal";
resize: function(){
var new_margin = Math.ceil(($(window).height() - $(modalId).find('.modal-dialog').height()) / 2);
$(modalId).find('.modal-dialog').css('margin-top', new_margin + 'px');
}
$(window).resize(function(){
resize();
});
$(modalId).on('shown.bs.modal', function(){
resize();
});
});
i++ is known as Post Increment whereas ++i is called Pre Increment.
i++
i++
is post increment because it increments i
's value by 1 after the operation is over.
Lets see the following example:
int i = 1, j;
j = i++;
Here value of j = 1
but i = 2
. Here value of i
will be assigned to j
first then i
will be incremented.
++i
++i
is pre increment because it increments i
's value by 1 before the operation.
It means j = i;
will execute after i++
.
Lets see the following example:
int i = 1, j;
j = ++i;
Here value of j = 2
but i = 2
. Here value of i
will be assigned to j
after the i
incremention of i
.
Similarly ++i
will be executed before j=i;
.
For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one.. doesn't matter. It will execute your for loop same no. of times.
for(i=0; i<5; i++)
printf("%d ",i);
And
for(i=0; i<5; ++i)
printf("%d ",i);
Both the loops will produce same output. ie 0 1 2 3 4
.
It only matters where you are using it.
for(i = 0; i<5;)
printf("%d ",++i);
In this case output will be 1 2 3 4 5
.
In HTML:
<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button>
In Jquery write this function:
function AddButtonClick(){
//change text from add to Update
$("#AddButton").text('Update');
}
=IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE)
, and choose to fill green when this is true=IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE)
and choose to fill red when this is true.More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF
formula to return true or false based on the values of any cells.
You just need to specify text-decoration: underline;
with pseudo-class :hover
.
<span class="underline-on-hover">Hello world</span>
.underline-on-hover:hover {
text-decoration: underline;
}
I have whipped up a working Code Pen Demo.
Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()
Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child. So if,
pid=fork();
If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them. Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.
When we test the value of pid to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.
These remaps work like a charm for me:
vmap <C-c> "*y " Yank current selection into system clipboard
nmap <C-c> "*Y " Yank current line into system clipboard (if nothing is selected)
nmap <C-v> "*p " Paste from system clipboard
So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.
This is also useful to copy text from Vim to clipboard.
Source: Copy and paste between sessions using a temporary file
Not really sure what you meant by "the caption in the middle", but here's one solution to get your images appear side by side, using the excellent display:inline-block
:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<style>
div.container {
display:inline-block;
}
p {
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 1</p>
</div>
<div class="container">
<img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200" />
<p>This is image 2</p>
</div>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 3</p>
</div>
</div>
</body>
</html>
I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:
set serveroutput on
create type number_list as table of number;
-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined
is
mystring varchar2(2000):= i_csv;
begin
for r in
( select regexp_substr(mystring,'[^,]+',1,level) element
from dual
connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
)
loop
--dbms_output.put_line(r.element);
pipe row(to_number(r.element, '999999.99'));
end loop;
end;
/
insert into foo
select column_a,column_b from
(select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a
,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
where a.rn = b.rn
;
I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system. Replaces AT.exe.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task immediately.
/End Stops the currently running scheduled task.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
+-------------------------------------+
¦ Executed Wed 02/29/2012 10:48:36.65 ¦
+-------------------------------------+
It's quite interesting and makes me feel so powerful. :)
I think that you had intialized a 3d array but you are trying to access an array with 4 dimension.
It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.
In angularjs this should works:
event.preventDefault();
event.stopPropagation();
In Numbers, click on the chart. Then in the BOTTOM LEFT corner there is the the option to either 'Plot Rows as Series'or 'Plot Columns as series'
This might be seen as a little complex but does exactly what you want
SELECT
DISTINCT(p.`ProductID`) AS ProductID,
SUM(pl.CashAmount) AS Cash,
SUM(pr.CashAmount) AS `Check`,
SUM(px.CashAmount) AS `Credit Card`,
SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
`payments` AS p
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl
ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr
ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px
ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;
Output
ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
3 | 20 | 15 | 25 | 60
4 | 5 | 6 | 7 | 18
The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence
You can also use '.array'.Refrence
Pandas .as_matrix deprecated since version 0.23.0.
Sometimes there is permission errors. Try:
sudo pip install simplejson
Hope it helps.
I recommend* URLify for PHP (480+ stars on Github) - "the PHP port of URLify.js from the Django project. Transliterates non-ascii characters for use in URLs".
Basic usage:
To generate slugs for URLs:
<?php
echo URLify::filter (' J\'étudie le français ');
// "jetudie-le-francais"
echo URLify::filter ('Lo siento, no hablo español.');
// "lo-siento-no-hablo-espanol"
?>
To generate slugs for file names:
<?php
echo URLify::filter ('????.jpg', 60, "", true);
// "foto.jpg"
?>
*None of the other suggestions matched my criteria:
As a bonus, URLify also removes certain words and strips away all characters not transliterated.
Here is a test case with tons of foreign characters being transliterated properly using URLify: https://gist.github.com/motin/a65e6c1cc303e46900d10894bf2da87f
If you're looking to get promise in resource call, you should use
Regions.query().$q.then(function(){ .... })
Update : the promise syntax is changed in current versions which reads
Regions.query().$promise.then(function(){ ..... })
Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.
I had the same error problem using Code Blocks rev 13.12. I may be wrong here since I am less than a beginner :)
My problem was that I accidentally capitalized "M" in Main() instead of ALL lowercase = main() - once corrected, it worked!!!
I noticed that you have "int main()" instead of "main()". Is this the problem, or is it supposed to be that way?
Hope I could help...
ProGuard will do it for you on your release build and now the good news from android.com:
http://developer.android.com/tools/help/proguard.html
The ProGuard tool shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names. The result is a smaller sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are Licensing Your Applications.
ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not have to deal with obfuscated code when you build your application in debug mode. Having ProGuard run is completely optional, but highly recommended.
This document describes how to enable and configure ProGuard as well as use the retrace tool to decode obfuscated stack traces
How about using express module?
var app = require('express')();
app.get('/',function(request,response){
response.sendFile(__dirname+'/XXX.html');
});
app.listen('8000');
then, you can use browser to get /localhost:8000
As odd as it sounds, at least for Safari in iOS 10.2, double tap to zoom is magically disabled if your element or any of its ancestors have one of the following:
cursor: pointer
set in CSSIn management studio you can set the timeout in seconds. menu Tools => Options set the field and then Ok
Did someone mention code_complete?
But you did not like ctags, so this is probably not what you are looking for...
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim
:
input = input.trim();
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.
Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:
EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!
Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
End Function
@kashesandr's solution worked for me but to hide horizontal scrollbar I added one more style for body. here is complete solution:
CSS
<style>
/* prevent layout shifting and hide horizontal scroll */
html {
width: 100vw;
}
body {
overflow-x: hidden;
}
</style>
JS
$(function(){
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
}
});
});
JS Only Solution (when 2nd modal opened from 1st modal):
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
$('body').css('padding-right', 17);
}
});
First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.
After locating the webpage, tap on the arrow icon at the top of your screen.
In the drop-down menu, tap on the Add to Home Screen option.
The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.
A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.
Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:
<meta name="apple-mobile-web-app-capable" content="yes">
You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.
From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\NOLA BOOTHE\My Documents\operating system"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
if both columns are strings, you can concatenate them directly:
df["period"] = df["Year"] + df["quarter"]
If one (or both) of the columns are not string typed, you should convert it (them) first,
df["period"] = df["Year"].astype(str) + df["quarter"]
If you need to join multiple string columns, you can use agg
:
df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1)
Where "-" is the separator.
Environment.NewLine
will return the newline character for the corresponding platform in which your code is running
you will find this very useful when you deploy your code in linux on the Mono framework
Yes, the DataTable.Select
method supports boolean operators in the same way that you would use them in a "real" SQL statement:
DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");
See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select
method.
Different types to check the values exists
d = {"key1":"value1", "key2":"value2"}
"value10" in d.values()
>> False
What if list of values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6']}
"value4" in [x for v in test.values() for x in v]
>>True
What if list of values with string values
test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6'], 'key5':'value10'}
values = test.values()
"value10" in [x for v in test.values() for x in v] or 'value10' in values
>>True
It is not the answer you probably want, but why hide what you're trying to make public?
My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
From the information available on accessibility and the use of tooltips making them larger with the use of CR or line break is appreciated, the fact that the various browsers cannot/will not agree on basics shows that they don't much care about accessibility.
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span
or div
, for example.
You can also use the info provided by a php exception, it's an elegant solution:
function GetCallingMethodName(){ $e = new Exception(); $trace = $e->getTrace(); //position 0 would be the line that called this function so we ignore it $last_call = $trace[1]; print_r($last_call); } function firstCall($a, $b){ theCall($a, $b); } function theCall($a, $b){ GetCallingMethodName(); } firstCall('lucia', 'php');
And you get this... (voilà!)
Array ( [file] => /home/lufigueroa/Desktop/test.php [line] => 12 [function] => theCall [args] => Array ( [0] => lucia [1] => php ) )
The best answer was the first one.
You are using:
It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction
class that contains two integers, a numerator and denominator, your __repr__()
method would look like this:
# in the definition of Fraction class
def __repr__(self):
return "Fraction(%d, %d)" % (self.numerator, self.denominator)
Assuming that the constructor takes those two values.
From SQL Server point of view:
Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.
You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).
Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.
Container(
height: 50,
// margin: EdgeInsets.only(top: 20),
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32)),
child: TextFormField(
cursorColor: Colors.black,
// keyboardType: TextInputType.,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(18),
),
),
),
Undefined offset means there's an empty array key for example:
$a = array('Felix','Jon','Java');
// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];
You can solve the problem using a loop (while):
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
// Increase count by 1, thus, $i=1
$i++;
$groupname[$i] = base64_decode(base64_decode($row['groupname']));
// Set the first position of the array to null or empty
$groupname[0] = "";
}
var p =[{"username":"ordermanageadmin","user_id":"2","resource_id":"Magento_Sales::actions"},_x000D_
{"username":"ordermanageadmin_1","user_id":"3","resource_id":"Magento_Sales::actions"}]_x000D_
for(var value in p) {_x000D_
for (var key in value) {_x000D_
if (p.hasOwnProperty(key)) {_x000D_
console.log(key + " -> " + p[key]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
Below are two answers. First is a suggestion to use a more secure/flexible solution like ssh/scp/sftp. Second is an explanation of how to run ftp in batch mode.
You really should use SSH/SCP/SFTP for this rather than FTP. SSH/SCP have the benefits of being more secure and working with public/private keys which allows it to run without a username or password.
You can send a single file:
scp <file to upload> <username>@<hostname>:<destination path>
Or a whole directory:
scp -r <directory to upload> <username>@<hostname>:<destination path>
For more details on setting up keys and moving files to the server with RSYNC, which is useful if you have a lot of files to move, or if you sometimes get just one new file among a set of random files, take a look at:
http://troy.jdmz.net/rsync/index.html
You can also execute a single command after sshing into a server:
From man ssh
ssh [...snipped...] hostname [command] If command is specified, it is executed on the remote host instead of a login shell.
So, an example command is:
ssh [email protected] bunzip file_just_sent.bz2
If you can use SFTP with keys to gain the benefit of a secured connection, there are two tricks I've used to execute commands.
First, you can pass commands using echo and pipe
echo "put files*.xml" | sftp -p -i ~/.ssh/key_name [email protected]
You can also use a batchfile with the -b
parameter:
sftp -b batchfile.txt ~/.ssh/key_name [email protected]
If you understand that FTP is insecure and more limited and you really really want to script it...
There's a great article on this at http://www.stratigery.com/scripting.ftp.html
#!/bin/sh
HOST='ftp.example.com'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
binary
put $FILE
quit
END_SCRIPT
exit 0
The -n
to ftp ensures that the command won't try to get the password from the current terminal. The other fancy part is the use of a heredoc: the <<END_SCRIPT
starts the heredoc and then that exact same END_SCRIPT
on the beginning of the line by itself ends the heredoc. The binary
command will set it to binary mode which helps if you are transferring something other than a text file.
Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.
Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.
A vectorized, pandas solution is very simple:
df['date'] - pd.DateOffset(months=1)
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir")
directory. This should be the working directory or the directory you ran the java command from.
Both ways are correct.
If you need to do something with the Exception object in the catch block then you should use
try {
// code....
}
catch (Exception ex){}
and then use ex
in the catch block.
Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.
Trim your String value by creating a trim function
var text = " ";
if($.trim(text.length == 0){
console.log("Text is empty");
}
else
{
console.log("Text is not empty");
}
I could totally be missing something here, but this solution seems a lot simpler than many others proposed.
extension UIPageViewController {
func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
if let currentViewController = viewControllers?[0] {
if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
}
}
}
}
If the button tag is inside the div element who contains the modal, you can do something like:
<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>
RGB Luminance value = 0.3 R + 0.59 G + 0.11 B
http://www.scantips.com/lumin.html
If you're looking for how close to white the color is you can use Euclidean Distance from (255, 255, 255)
I think RGB color space is perceptively non-uniform with respect to the L2 euclidian distance. Uniform spaces include CIE LAB and LUV.
I came across this when upgrading from 5.8 to 6.x.
I had str_slug()
in config/cache.php
and config/session.php
.
I have changed it to Str::slug()
and the error has disappeared.
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
You can use Enumeration
:
Hashtable<Integer, String> table = ...
Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
Integer key = enumKey.nextElement();
String val = table.get(key);
if(key==0 && val.equals("0"))
table.remove(key);
}
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
This only works for powers of two (and frequently only positive ones) because they have the unique property of having only one bit set to '1' in their binary representation. Because no other class of numbers shares this property, you can't create bitwise-and expressions for most modulus expressions.
One of the mistakes is setting components
as array instead of object!
This is wrong:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: [
ChildComponent
],
props: {
...
}
};
</script>
This is correct:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
props: {
...
}
};
</script>
Note: for components that use other ("child") components, you must also specify a components
field!
It's easy with rules:
CREATE RULE file_insert_defer AS ON INSERT TO file
WHERE (EXISTS ( SELECT * FROM file WHERE file.id = new.id)) DO INSTEAD NOTHING
But it fails with concurrent writes ...
In my case, the problem was in the xml
code somehow.
My web.xml
file looked like this:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>index</servlet-name>
<jsp-file>index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
but I changed it to look like
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
and now the server loads up properly. Strange.
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));
When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId
:
Attribute VB_PredeclaredId = False
Set it to True
, save, and re-import the module into your VBA project.
Classes with a PredeclaredId
have a "global instance" that you get for free - exactly like UserForm
modules (export a user form, you'll see its predeclaredId attribute is set to true).
A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!
Instead, you leverage that default instance to implement your factory method:
[Employee
class]
'@PredeclaredId
Option Explicit
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As Employee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
With that, you can do this:
Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)
Employee.Create
is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.
Problem is, this is also perfectly legal:
Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)
And that sucks, because now you have a confusing API. You could use '@Description
annotations / VB_Description
attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.
Besides, the Property Let
members are accessible, so your Employee
instance is mutable:
empl.Name = "Jane" ' Johnny no more!
The trick is to make your class implement an interface that only exposes what needs to be exposed:
[IEmployee
class]
Option Explicit
Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property
And now you make Employee
implement IEmployee
- the final class might look like this:
[Employee
class]
'@PredeclaredId
Option Explicit
Implements IEmployee
Private Type TEmployee
Name As String
Age As Integer
End Type
Private this As TEmployee
Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
With New Employee
.Name = emplName
.Age = emplAge
Set Create = .Self 'returns the newly created instance
End With
End Function
Public Property Get Self() As IEmployee
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal value As String)
this.Name = value
End Property
Public Property Get Age() As String
Age = this.Age
End Property
Public Property Let Age(ByVal value As String)
this.Age = value
End Property
Private Property Get IEmployee_Name() As String
IEmployee_Name = Name
End Property
Private Property Get IEmployee_Age() As Integer
IEmployee_Age = Age
End Property
Notice the Create
method now returns the interface, and the interface doesn't expose the Property Let
members? Now calling code can look like this:
Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)
And since the client code is written against the interface, the only members empl
exposes are the members defined by the IEmployee
interface, which means it doesn't see the Create
method, nor the Self
getter, nor any of the Property Let
mutators: so instead of working with the "concrete" Employee
class, the rest of the code can work with the "abstract" IEmployee
interface, and enjoy an immutable, polymorphic object.
use $unwind you will get the first object instead of array of objects
query:
db.getCollection('vehicles').aggregate([
{
$match: {
status: "AVAILABLE",
vehicleTypeId: {
$in: Array.from(newSet(d.vehicleTypeIds))
}
}
},
{
$lookup: {
from: "servicelocations",
localField: "locationId",
foreignField: "serviceLocationId",
as: "locations"
}
},
{
$unwind: "$locations"
}
]);
result:
{
"_id" : ObjectId("59c3983a647101ec58ddcf90"),
"vehicleId" : "45680",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Isuzu/2003-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
{
"_id" : ObjectId("59c3983a647101ec58ddcf91"),
"vehicleId" : "81765",
"regionId" : 1.0,
"vehicleTypeId" : "10TONBOX",
"locationId" : "100",
"description" : "Hino/2004-10 Ton/Box",
"deviceId" : "",
"earliestStart" : 36000.0,
"latestArrival" : 54000.0,
"status" : "AVAILABLE",
"accountId" : 1.0,
"locations" : {
"_id" : ObjectId("59c3afeab7799c90ebb3291f"),
"serviceLocationId" : "100",
"regionId" : 1.0,
"zoneId" : "DXBZONE1",
"description" : "Masafi Park Al Quoz",
"locationPriority" : 1.0,
"accountTypeId" : 0.0,
"locationType" : "DEPOT",
"location" : {
"makani" : "",
"lat" : 25.123091,
"lng" : 55.21082
},
"deliveryDays" : "MTWRFSU",
"timeWindow" : {
"timeWindowTypeId" : "1"
},
"address1" : "",
"address2" : "",
"phone" : "",
"city" : "",
"county" : "",
"state" : "",
"country" : "",
"zipcode" : "",
"imageUrl" : "",
"contact" : {
"name" : "",
"email" : ""
},
"status" : "",
"createdBy" : "",
"updatedBy" : "",
"updateDate" : "",
"accountId" : 1.0,
"serviceTimeTypeId" : "1"
}
}
This can be done even without renaming the local branch in three simple steps:
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
I ended up trying something easy by resetting the Debug perspective, which seemed to work:
Window => Perspective => Reset Perspective...
Thanks for the comments.
Use robocopy
. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy
. (xcopy
has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).
robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat
Note that using /purge
on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /?
for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b
instead of /zb
.
(?!Andrea).{6}
Assuming your regexp engine supports negative lookaheads..
Edit: ..or maybe you'd prefer to use [A-Za-z]{6}
in place of .{6}
Edit (again): Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching, they leave that to whatever language you are using them with.
Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".
If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"
I've used this process to attach a 3rd party Jar to an Android project in IDEA.
The library should now be recognised.
You can use the nth-child
CSS selector to hide a whole column:
#myTable tr > *:nth-child(2) {
display: none;
}
This works under assumption that a cell of column N (be it a th
or td
) is always the Nth child element of its row.
?
If you want the column number to be dynamic, you could do that using querySelectorAll
or any framework presenting similar functionality, like jQuery
here:
$('#myTable tr > *:nth-child(2)').hide();
(The jQuery solution also works on legacy browsers that don't support nth-child
).
something like this?
DECLARE maxval, val, @ind INT;
SELECT MAX(ID) as maxval FROM table;
while (ind <= maxval ) DO
select `value` as val from `table` where `ID`=ind;
CALL fn(val);
SET ind = ind+1;
end while;
Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.
This method will walk through object properties and write them to the console with increasing indent:
function enumerate(o,s){
//if s isn't defined, set it to an empty string
s = typeof s !== 'undefined' ? s : "";
//if o is null, we need to output and bail
if(typeof o == "object" && o === null){
console.log(s+k+": null");
} else {
//iterate across o, passing keys as k and values as v
$.each(o, function(k,v){
//if v has nested depth
if(typeof v == "object" && v !== null){
//write the key to the console
console.log(s+k+": ");
//recursively call enumerate on the nested properties
enumerate(v,s+" ");
} else {
//log the key & value
console.log(s+k+": "+String(v));
}
});
}
}
Just pass it the object you want to iterate through:
var response = $.ajax({
url: myurl,
dataType: "json"
})
.done(function(a){
console.log("Returned values:");
enumerate(a);
})
.fail(function(){ console.log("request failed");});
Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS
variant or a LEFT JOIN
), but your query is perfectly legit.
Be aware of pitfalls with NOT IN
, though, when involving any NULL
values:
Variant with LEFT JOIN:
SELECT *
FROM friend f
LEFT JOIN likes l USING (id1, id2)
WHERE l.id1 IS NULL;
See @Michal's answer for the NOT EXISTS
variant.
A more detailed assessment of four basic variants:
A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication()
and getApplicationContext()
return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext()
and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext()
exist in the first place ?
getApplication()
is only available in the Activity class and the Service class, whereas getApplicationContext()
is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext()
. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext()
delegates it's call to baseContext.getApplicationContext()
.
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass
Application
. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given aContext
which internally usesContext.getApplicationContext()
when first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
In my case, the only option was to remove the VM and download it again. No re-configuration of the host-only adapter did not help, I used different addressing of DHCP. Virtual Box I updated to version 4.3.4 and Genymotion to 2.0.2
using this we can add two array with out any loop.
I believe if you have 2 arrays of the same type that you want to combine into one of array, there's a very simple way to do that.
Here's the code:
String[] TextFils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
String[] finalArray = TextFils.Concat(ExcelFils).ToArray();
or
String[] Fils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
Fils = Fils.Concat(ExcelFils).ToArray();
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:
public abstract class EO {
@Autowired
protected SmsNotificationService smsNotificationService;
@Autowired
protected SendEmailService sendEmailService;
...
protected abstract void executeOperation(GenericMessage gMessage);
}
public final class OperationsExecutor {
public enum OperationsType {
ENROLL, CAMPAIGN
}
private OperationsExecutor() {
}
public static Object delegateOperation(OperationsType type, Object obj)
{
switch(type) {
case ENROLL:
if (obj == null) {
return new EnrollOperation();
}
return EnrollOperation.validateRequestParams(obj);
case CAMPAIGN:
if (obj == null) {
return new CampaignOperation();
}
return CampaignOperation.validateRequestParams(obj);
default:
throw new IllegalArgumentException("OperationsType not supported.");
}
}
}
@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
@Override
public void executeOperation(GenericMessage genericMessage) {
LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
}
}
Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)**
annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.
<context:annotation-config />
<context:component-scan base-package="com.xyz" />
I also tried these other references to find a solution:
Please try using **@Configurable(dependencyCheck = true)**
and update this post, I might try helping you if you face any problems.
import numpy
print numpy.__version__
If you are a user of MacPorts, you may simply install usbutils
sudo port install usbutils
If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.
@Column
AnnotationThe nullable
attribute of the @Column
annotation has two purposes:
The HBM2DDL schema generation tool translates the @Column(nullable = false)
entity attribute to a NOT NULL
constraint for the associated table column when generating the CREATE TABLE
statement.
As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.
When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false)
entity attribute:
new Nullability( session ).checkNullability( values, persister, true );
If the validation fails, Hibernate will throw a PropertyValueException
, and prevents the INSERT or UPDATE statement to be executed needesly:
if ( !nullability[i] && value == null ) {
//check basic level one nullablilty
throw new PropertyValueException(
"not-null property references a null or transient value",
persister.getEntityName(),
persister.getPropertyNames()[i]
);
}
@NotNull
AnnotationThe @NotNull
annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.
When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation
when validating the entity.
You could use memset, if you sure about the length.
memset(ptr, 0x00, length)
You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.
If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.
Login using the system maintenance user and password created when you installed phpMyAdmin.
It can be found in the debian.cnf file at /etc/mysql then you will have total access.
cd /etc/mysql
sudo nano debian.cnf
Just look - don't change anything!
[mysql_upgrade]
host = localhost
user = debian-sys-maint <----use this user
password = s0meRaND0mChar$s <----use this password
socket = /var/run/mysqld/mysqld.sock
Worked for me.
Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945
Also, the Angular docs now have a cookbook example that uses a Subject.
Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.
Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.
nav.service.ts
import {EventEmitter} from 'angular2/core';
export class NavService {
navchange: EventEmitter<number> = new EventEmitter();
constructor() {}
emitNavChangeEvent(number) {
this.navchange.emit(number);
}
getNavChangeEmitter() {
return this.navchange;
}
}
components.ts
import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number = 0;
subscription: any;
constructor(private navService:NavService) {}
ngOnInit() {
this.subscription = this.navService.getNavChangeEmitter()
.subscribe(item => this.selectedNavItem(item));
}
selectedNavItem(item: number) {
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
`,
})
export class Navigation {
item = 1;
constructor(private navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navService.emitNavChangeEvent(item);
}
}
Guava also has Base64 (among other encodings and incredibly useful stuff)
Never mind, I figured it out - I used the Set()
method on Header()
(doh!)
My handler looks like this now:
func saveHandler(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
}
Maybe this will help someone as caffeine deprived as myself sometime :)
Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.
Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.
In regards to your error and what's missing in your code. m
is a name which is not defined for getmd5()
function.
No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)
First, you are not using hashlib.md5.hexdigest()
method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:
>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'
However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:
>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'
As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.
A simple solution could be something like that:
# Import hashlib library (md5 method is part of it)
import hashlib
# File to check
file_name = 'filename.exe'
# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'
# Open,close, read file and calculate MD5 on its contents
with open(file_name) as file_to_check:
# read contents of the file
data = file_to_check.read()
# pipe contents of the file through
md5_returned = hashlib.md5(data).hexdigest()
# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
print "MD5 verified."
else:
print "MD5 verification failed!."
Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.
Best of luck.
In addition to the accepted answer, there is a corner case when you should use filter instead of a list comprehension. If the list is unhashable you cannot directly process it with a list comprehension. A real world example is if you use pyodbc
to read results from a database. The fetchAll()
results from cursor
is an unhashable list. In this situation, to directly manipulating on the returned results, filter should be used:
cursor.execute("SELECT * FROM TABLE1;")
data_from_db = cursor.fetchall()
processed_data = filter(lambda s: 'abc' in s.field1 or s.StartTime >= start_date_time, data_from_db)
If you use list comprehension here you will get the error:
TypeError: unhashable type: 'list'
I had a similar issue but I was missing the (@Service or @Component) from the implementation of com.example.my.services.myUser.MyUserServiceImpl
You can't need using sections in partial view.
Include in your Partial View. It execute the function after jQuery loaded. You can alter de condition clause for your code.
<script type="text/javascript">
var time = setInterval(function () {
if (window.jQuery != undefined) {
window.clearInterval(time);
//Begin
$(document).ready(function () {
//....
});
//End
};
}, 10); </script>
Julio Spader
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
Easy way
MYSQL:
SELECT 'filds' FROM 'table' WHERE 'where' LIMIT 'offset','per_page'
MSSQL:
SELECT 'filds' FROM 'table' WHERE 'where' ORDER BY 'any' OFFSET 'offset'
ROWS FETCH NEXT 'per_page' ROWS ONLY
ORDER BY is mandatory
The plugin vagrant-vbguest solved my problem:
$ vagrant plugin install vagrant-vbguest
Output:
$ vagrant reload
==> default: Attempting graceful shutdown of VM...
...
==> default: Machine booted and ready!
GuestAdditions 4.3.12 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Exporting NFS shared folders...
==> default: Preparing to edit /etc/exports. Administrator privileges will be required...
==> default: Mounting NFS shared folders...
==> default: VM already provisioned. Run `vagrant provision` or use `--provision` to force it
Just make sure you are running the latest version of VirtualBox
Give the div "runat="server"
and an id
and you can reference it in your code behind
.
<div runat="server" id="theDiv">
In code behind:
{
theDiv.Visible = false;
}
If you don't want to show the series names in the legend you can disable them by setting showInLegend:false
.
example:
series: [{
showInLegend: false,
name: "<b><?php echo $title; ?></b>",
data: [<?php echo $yaxis; ?>],
}]
You get other options here.
I will group the options based on output. Assume the following vector for all the examples.
v <- c('z', 'a','b','a','e')
For checking presence:
%in%
> 'a' %in% v
[1] TRUE
any()
> any('a'==v)
[1] TRUE
is.element()
> is.element('a', v)
[1] TRUE
For finding first occurance:
match()
> match('a', v)
[1] 2
For finding all occurances as vector of indices:
which()
> which('a' == v)
[1] 2 4
For finding all occurances as logical vector:
==
> 'a' == v
[1] FALSE TRUE FALSE TRUE FALSE
Edit: Removing grep() and grepl() from the list for reason mentioned in comments
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.
f is assigned the nearest value that is not equivalent to false. So 0, false, null, undefined, are all passed over:
alert(null || undefined || false || '' || 0 || 4 || 'bar'); // alerts '4'
Update:
As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity
Dictionary in the info.plist
.
It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary
Loads as well.
info.plist screenshot
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v
and \h
, as well as the generic whitespace character class \s
The cleanest solution is to use the horizontal whitespace character class \h
. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters
U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)
U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE
The vertical space pattern \v
is less useful, but matches these characters
U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)
U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR
There are seven vertical whitespace characters which match \v
and eighteen horizontal ones which match \h
. \s
matches twenty-three characters
All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h
also matches U+00A0 NO-BREAK SPACE, and \v
also matches U+0085 NEXT LINE, neither of which are matched by \s
The most important difference is this:
In case of persist
method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)
But in case of merge
method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)
I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash
Then I use this function defined in my .profile to simplify running symbolicatecrash:
function desym
{
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}
The arguments added there may help you.
You can check to make sure spotlight "sees" your dysm files by running the command:
mdfind 'com_apple_xcode_dsym_uuids = *'
Look for the dsym you have in your directory.
NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:
/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
You can use -webkit-border-radius: 0;
. Like this:-
-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;
This will give square corners as well as dropdown arrows. Using -webkit-appearance: none;
is not recommended as it will turn off all the styling done by Chrome.
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
Ultimately, .keystore
and .jks
are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore
: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks
extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).
In Java, the word keystore can have either of the following meanings, depending on the context:
When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.
Java uses its KeyStore
class and related API to make use of a keystore (whether it's file based or not). JKS
is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:
.jks
for type "JKS"
,.p12
or .pfx
for type "PKCS12"
(the specification name is PKCS#12, but the #
is not used in the Java keystore type name).In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks
extension), which is frequently used for Android applications.
That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.
u'AB'
is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:
L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)
AB, AB, AB, AB
There is no u''
in memory. It is just the way to represent the unicode
object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L
is equivalent to print "[%s]" % ", ".join(map(repr, L))
i.e., repr()
function is called for each list item:
print L
print "[%s]" % ", ".join(map(repr, L))
[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']
If you are working in a REPL then a customizable sys.displayhook
is used that calls repr()
on each object by default:
>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB
Don't encode to bytes. Print unicode directly.
In your specific case, I would create a Python list and use json.dumps()
to serialize it instead of using string formatting to create JSON text:
#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
for player in players]
print test
print json.dumps(test)
[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]
Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl
as appropriate).
At the command prompt, navigate to the directory containing get-pip.py
and runpython get-pip.py
which creates files in C:\Python27\Scripts
, including pip2
, pip2.7
and pip
.
Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl
into the above directory (C:\Python27\Scripts
)
Still at the command prompt, navigate to the above directory and run:
pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"
add #include <iostream>
to the start of io.cpp
too.
Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html
It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
console.log('Settings saved');
});
// Read it using the storage API
chrome.storage.sync.get(['foo', 'bar'], function(items) {
message('Settings retrieved', items);
});
To use it, make sure you define it in the manifest:
"permissions": [
"storage"
],
There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"
Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.
Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.
The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:
contentscript.js
chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
console.log(response.status);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getStatus")
sendResponse({status: localStorage['status']});
else
sendResponse({}); // snub them.
});
You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.
I hope that helped solve your problem.
To be fancy and generic ...
contentscript.js
chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
console.log(response.data);
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
I would like to add something to the very helpful answer above. If you don't know the height you'll end up with since your views .getHeight() returns 0 you can do the following to get the height:
contentView.measure(DUMMY_HIGH_DIMENSION, DUMMY_HIGH_DIMENSION);
int finalHeight = view.getMeasuredHeight();
Where DUMMY_HIGH_DIMENSIONS is the width/height (in pixels) your view is constrained to ... having this a huge number is reasonable when the view is encapsulated with a ScrollView.
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
@Max: is right about the creation time.
However, if you want to calculate the elapsed days argument for one of the -atime
, -ctime
, -mtime
parameters, you can use the following expression
ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find
's date rounding.)
So, to find any file modified on September 24th, 2008, the command would be:
find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
This will work if your version of find
doesn't support the -newerXY
predicates mentioned in @Arve:'s answer.
From the terminal, just Run the command on your command prompt window. (Not inside psql).
createdb <user>
And then try to run postgres again.
In my case I just removed line with setHasStableIds(true);
Defining useful repr() methods for your classes (so you can see what an object is) and using repr() or "%r" % (...) or "...{0!r}..".format(...) in your debug messages/logs is IMHO a key to efficient debugging.
Also, the debuggers mentioned in other answers will make use of the repr() methods.
If you are averse to boost, you can use regular old operator>>
, along with std::noskipws
:
EDIT: updates after testing.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
void split(const std::string& str, std::vector<std::string>& v) {
std::stringstream ss(str);
ss >> std::noskipws;
std::string field;
char ws_delim;
while(1) {
if( ss >> field )
v.push_back(field);
else if (ss.eof())
break;
else
v.push_back(std::string());
ss.clear();
ss >> ws_delim;
}
}
int main() {
std::vector<std::string> v;
split("hello world how are you", v);
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
std::cout << "\n";
}
What is this? :)
background-color: #D8F0DA;
Try
background: none
And override works only if property is exactly the same.
background doesn't override background-color.
If you want alpha transparency, then use something like this
background: rgba(100, 100, 100, 0.5);
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
if(session_status()!=PHP_SESSION_ACTIVE) session_start()
Remove the get_figure
and just use sns_plot.savefig('output.png')
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', height=2.5)
sns_plot.savefig("output.png")
As already stated by Jason Cohen, the Java Language Specification defines what a legal identifier is in section 3.8:
"An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. [...] A 'Java letter' is a character for which the method Character.isJavaIdentifierStart(int) returns true. A 'Java letter-or-digit' is a character for which the method Character.isJavaIdentifierPart(int) returns true."
This hopefully answers your second question. Regarding your first question; I've been taught both by teachers and (as far as I can remember) Java compilers that a Java class name should be an identifier that begins with a capital letter A-Z, but I can't find any reliable source on this. When trying it out with OpenJDK there are no warnings when beginning class names with lower-case letters or even a $-sign. When using a $-sign, you do have to escape it if you compile from a bash shell, however.
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Best way would be
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
:)
Why not simply use angular.isObject
with negation? e.g.
if (!angular.isObject(obj)) {
return;
}