SELECT COUNT(1) FROM MyTable WHERE ...
will loop thru all the records. This is the reason it is bad to use for record existence.
I would use
SELECT TOP 1 * FROM MyTable WHERE ...
After finding 1 record, it will terminate the loop.
I found this link windows.h and winsock2.h which has an alternative that worked great for me:
#define _WINSOCKAPI_ // stops windows.h including winsock.h
#include <windows.h>
#include <winsock2.h>
I was having trouble finding where the issue occurred but by adding that #define I was able to build without figuring it out.
Create a user first. You must do this as user postgres. Because the postgres system account has no password assigned, you can either set a password first, or you go like this:
sudo /bin/bash
# you should be root now
su postgres
# you are postgres now
createuser --interactive
and the programm will prompt you.
Creating colnames with iterating
df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)
# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []
to_html()
operations
print(df.to_html())
# <table border="1" class="dataframe">
# <thead>
# <tr style="text-align: right;">
# <th></th>
# <th>colname_0</th>
# <th>colname_1</th>
# <th>colname_2</th>
# <th>colname_3</th>
# <th>colname_4</th>
# </tr>
# </thead>
# <tbody>
# </tbody>
# </table>
this seems working
print(type(df.to_html()))
# <class 'str'>
when you create df like this
df = pd.DataFrame(columns=COLUMN_NAMES)
it has 0 rows × n columns
, you need to create at least one row index by
df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
now it has 1 rows × n columns
. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).
That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:
("This is the first line of my text, "
"which will be joined to a second.")
Or with line ending continuations, which is a little more fragile, as this works:
"This is the first line of my text, " \
"which will be joined to a second."
But this doesn't:
"This is the first line of my text, " \
"which will be joined to a second."
See the difference? No? Well you won't when it's your code either.
The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.
Alternatively, you can join explicitly using the concatenation operator (+
):
("This is the first line of my text, " +
"which will be joined to a second.")
Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.
Finally, you can use triple-quoted strings:
"""This is the first line of my text
which will be joined to a second."""
This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.
"""This is the first line of my text \
which will be joined to a second."""
This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.
Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.
SELECT count(*) -- or count(myCol)
FROM <table name> -- replace <table name> with your table
WHERE myCol = true;
Here's a way with Windowing Function:
SELECT DISTINCT *, count(*) over(partition by myCol)
FROM <table name>;
-- Outputs:
-- --------------
-- myCol | count
-- ------+-------
-- f | 2
-- t | 3
-- | 1
Click on settings in top tool bar;
Click on debugger;
In tree, highlight "gdb/cdb debugger" by clicking it
Click "create configuration"
Add "gdb.exe" (no quotes) as a configuration
Delete default configuration
Click on gdb.exe
that you created in the tree (it should be the only one) and a dialogue will appear to the right for "executable path" with a button to the right.
Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe
(it sort of finds itself).
As mentioned, one way is to use
new Integer(my_int_value)
But you should not call the constructor for wrapper classes directly
So, modify the code accordingly:
mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.
You add this line to activate it:
$('[data-toggle="popover"]').popover();
And these settings to your anchor links:
data-toggle="popover" data-trigger="hover"
See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.
Adapted from answers by Ants Aasma and shawnrad:
nonprintable = set(map(chr, list(range(0,32)) + list(range(127,160))))
ord_dict = {ord(character):None for character in nonprintable}
def filter_nonprintable(text):
return text.translate(ord_dict)
#use
str = "this is my string"
str = filter_nonprintable(str)
print(str)
tested on Python 3.7.7
Since ES6 filter
supports pointy arrow notation (like LINQ):
So it can be boiled down to following one-liner.
['a','b',1].filter(item => typeof item ==='string');
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
I was recently experimenting in order to answer this question I was asking myself. Here are my conclusions:
Since in Windows, you can't be sure that the uname
command is available, you can use gcc -dumpmachine
. This will display the compiler target.
There may be also a problem when using uname
if you want to do some cross-compilation.
Here's a example list of possible output of gcc -dumpmachine
:
You can check the result in the makefile like this:
SYS := $(shell gcc -dumpmachine)
ifneq (, $(findstring linux, $(SYS)))
# Do Linux things
else ifneq(, $(findstring mingw, $(SYS)))
# Do MinGW things
else ifneq(, $(findstring cygwin, $(SYS)))
# Do Cygwin things
else
# Do things for others
endif
It worked well for me, but I'm not sure it's a reliable way of getting the system type. At least it's reliable about MinGW and that's all I need since it does not require to have the uname
command or MSYS package in Windows.
To sum up, uname
gives you the system on which you're compiling, and gcc -dumpmachine
gives you the system for which you are compiling.
Im using R Studio on a Mac and I couldn't find the Rconsole file. So I took a more brutal way and just deleted the unwanted language files from the R app. You just have to go to your Rapp in your application Folder, right click, show package content then /contents/Resources/. There are the language files e.g. English.lproj or in my case de.lproj wich I deleted. After restarting R, error messages appear in English.. Maybe thats helpful!
Well, it's just a javascript object, so you can manipulate data.items
just like you would an ordinary array. If you do:
data.items.pop();
your items
array will be 1 item shorter.
<div style="cursor: pointer;" onclick="theFunction()">
is the simplest thing that works.
Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it on a list apart for good practices on not just solving this particular problem but in markup design in general.
Each control deriving from Panel
implements distinct layout logic performed in Measure()
and Arrange()
:
Measure()
determines the size of the panel and each of its childrenArrange()
determines the rectangle where each control rendersThe last child of the DockPanel
fills the remaining space. You can disable this behavior by setting the LastChild
property to false
.
The StackPanel
asks each child for its desired size and then stacks them. The stack panel calls Measure()
on each child, with an available size of Infinity
and then uses the child's desired size.
A Grid
occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel
and then overriding MeasureOverride()
and ArrangeOverride()
.
See this article for a simple example.
in windows open windows powershell and go to the folder where sql files are then run this command
cat *.sql | C:\xampp\mysql\bin\mysql.exe -u username -p databasename
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
Set the ReadOnly attribute to true.
Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.
Here's my 2 cents:
IEnumerable<string> Split(string str, int chunkSize)
{
while (!string.IsNullOrWhiteSpace(str))
{
var chunk = str.Take(chunkSize).ToArray();
str = str.Substring(chunk.Length);
yield return new string(chunk);
}
}//Split
Just do System.out.println(e.getActionCommand());
inside actionPerformed(ActionEvent e)
function. This will tell you which command is just performed.
or
if(e.getActionCommand().equals("Add")){
System.out.println("Add button pressed");
}
I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?
I would suggest the latter. So in your form, create a property that wraps the Text
property of the TextBox
control in question:
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:
class SomeClass
{
private readonly YourFormClass form;
public SomeClass(YourFormClass form)
{
this.form = form;
}
private void SomeMethodDoingStuffWithText()
{
string firstName = form.FirstName;
form.FirstName = "some name";
}
}
An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):
interface IYourForm
{
string FirstName { get; set; }
}
In your form class:
class YourFormClass : Form, IYourForm
{
// lots of other code here
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
}
...and the class:
class SomeClass
{
private readonly IYourForm form;
public SomeClass(IYourForm form)
{
this.form = form;
}
// and so on
}
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
Doesn't need to. RequestMapping annotation supports wildcards and ant-style paths. Also looks like you just want a default view, so you can put
<mvc:view-controller path="/" view-name="welcome"/>
in your config file. That will forward all requests to the Root to the welcome view.
My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.
[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution
% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off
% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off
You can see for yourself which method agrees with the correct answer (red curve).
Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx)
which expresses the integral of the probability density function, i.e.
% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off
If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name
under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com
and one for redirect-to.final-destination.com
. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.
For .nupkg files I like to use:
Install-Package C:\Path\To\Some\File.nupkg
You need to use the proper git URL:
pip install git+https://github.com/jkbr/httpie.git#egg=httpie
Also see the VCS Support section of the pip documentation.
Don’t forget to include the egg=<projectname>
part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.
The way is
pip install [package_name] --upgrade
or in short
pip install [package_name] -U
Using sudo
will ask to enter your root password to confirm the action, but although common, is considered unsafe.
If you do not have a root password (if you are not the admin) you should probably work with virtualenv.
You can also use the user flag to install it on this user only.
pip install [package_name] --upgrade --user
Flexbox spec editor here.
This is an encouraged use of flexbox, but there are a few things you should tweak for best behavior.
Don't use prefixes. Unprefixed flexbox is well-supported across most browsers. Always start with unprefixed, and only add prefixes if necessary to support it.
Since your header and footer aren't meant to flex, they should both have flex: none;
set on them. Right now you have a similar behavior due to some overlapping effects, but you shouldn't rely on that unless you want to accidentally confuse yourself later. (Default is flex:0 1 auto
, so they start at their auto height and can shrink but not grow, but they're also overflow:visible
by default, which triggers their default min-height:auto
to prevent them from shrinking at all. If you ever set an overflow
on them, the behavior of min-height:auto
changes (switching to zero rather than min-content) and they'll suddenly get squished by the extra-tall <article>
element.)
You can simplify the <article>
flex
too - just set flex: 1;
and you'll be good to go. Try to stick with the common values in https://drafts.csswg.org/css-flexbox/#flex-common unless you have a good reason to do something more complicated - they're easier to read and cover most of the behaviors you'll want to invoke.
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
_x000D_
Atom does not have a specific comment-block function, but if you select more rows and then use the normal ctrl-/ (Windows or Linux) cmd-/ (Mac), it will comment all the lines.
how can i return a array in a c++ method and how must i declare it? int[] test(void); ??
This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer...
std::vector<>
, which grows dynamically to however many elements you encounter at runtime, or
std::array<>
(introduced with C++11), which always stores a number of elements specified at compile time,
...as they manage memory for you, ensuring correct behaviour and simplifying things considerably:
std::vector<int> fn()
{
std::vector<int> x;
x.push_back(10);
return x;
}
std::array<int, 2> fn2() // C++11
{
return {3, 4};
}
void caller()
{
std::vector<int> a = fn();
const std::vector<int>& b = fn(); // extend lifetime but read-only
// b valid until scope exit/return
std::array<int, 2> c = fn2();
const std::array<int, 2>& d = fn2();
}
The practice of creating a const
reference to the returned data can sometimes avoid a copy, but normally you can just rely on Return Value Optimisation, or - for vector
but not array
- move semantics (introduced with C++11).
If you really want to use an inbuilt array (as distinct from the Standard library class called array
mentioned above), one way is for the caller to reserve space and tell the function to use it:
void fn(int x[], int n)
{
for (int i = 0; i < n; ++i)
x[i] = n;
}
void caller()
{
// local space on the stack - destroyed when caller() returns
int x[10];
fn(x, sizeof x / sizeof x[0]);
// or, use the heap, lives until delete[](p) called...
int* p = new int[10];
fn(p, 10);
}
Another option is to wrap the array in a structure, which - unlike raw arrays - are legal to return by value from a function:
struct X
{
int x[10];
};
X fn()
{
X x;
x.x[0] = 10;
// ...
return x;
}
void caller()
{
X x = fn();
}
Starting with the above, if you're stuck using C++03 you might want to generalise it into something closer to the C++11 std::array
:
template <typename T, size_t N>
struct array
{
T& operator[](size_t n) { return x[n]; }
const T& operator[](size_t n) const { return x[n]; }
size_t size() const { return N; }
// iterators, constructors etc....
private:
T x[N];
};
Another option is to have the called function allocate memory on the heap:
int* fn()
{
int* p = new int[2];
p[0] = 0;
p[1] = 1;
return p;
}
void caller()
{
int* p = fn();
// use p...
delete[] p;
}
To help simplify the management of heap objects, many C++ programmers use "smart pointers" that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:
std::shared_ptr<int> p(new int[2], [](int* p) { delete[] p; } );
std::unique_ptr<int[]> p(new int[3]);
If you're stuck on C++03, the best option is to see if the boost library is available on your machine: it provides boost::shared_array
.
Yet another option is to have some static memory reserved by fn()
, though this is NOT THREAD SAFE, and means each call to fn()
overwrites the data seen by anyone keeping pointers from previous calls. That said, it can be convenient (and fast) for simple single-threaded code.
int* fn(int n)
{
static int x[2]; // clobbered by each call to fn()
x[0] = n;
x[1] = n + 1;
return x; // every call to fn() returns a pointer to the same static x memory
}
void caller()
{
int* p = fn(3);
// use p, hoping no other thread calls fn() meanwhile and clobbers the values...
// no clean up necessary...
}
You can store your settings info as Strings
of XML in the Settings.Default
. Create some classes to store your configuration data and make sure they are [Serializable]
. Then, with the following helpers, you can serialize instances of these objects--or List<T>
(or arrays T[]
, etc.) of them--to String
. Store each of these various strings in its own respective Settings.Default
slot in your WPF application's Settings
.
To recover the objects the next time the app starts, read the Settings
string of interest and Deserialize
to the expected type T
(which this time must be explcitly specified as a type argument to Deserialize<T>
).
public static String Serialize<T>(T t)
{
using (StringWriter sw = new StringWriter())
using (XmlWriter xw = XmlWriter.Create(sw))
{
new XmlSerializer(typeof(T)).Serialize(xw, t);
return sw.GetStringBuilder().ToString();
}
}
public static T Deserialize<T>(String s_xml)
{
using (XmlReader xw = XmlReader.Create(new StringReader(s_xml)))
return (T)new XmlSerializer(typeof(T)).Deserialize(xw);
}
If you would like to have a histogram of unique values here's oneliner
import numpy as np
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))
No. MySQL is not case sensitive, and neither is the SQL standard. It's just common practice to write the commands upper-case.
Now, if you are talking about table/column names, then yes they are, but not the commands themselves.
So
SELECT * FROM foo;
is the same as
select * from foo;
but not the same as
select * from FOO;
You need to set index=False
in to_excel
in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html
There is types.SimpleNamespace
class in Python 3.3+:
obj = someobject
obj.a = SimpleNamespace()
for p in params:
setattr(obj.a, p, value)
# obj.a.attr1
collections.namedtuple
, typing.NamedTuple
could be used for immutable objects. PEP 557 -- Data Classes suggests a mutable alternative.
For a richer functionality, you could try attrs
package. See an example usage.
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
Unit testing is directed at the smallest part of the implementation possible. In Java this means you are testing a single class. If the class depends on other classes these are faked.
When your test calls more than one class, it's an integration test.
Full test suites can take a long time to run, so after a change many teams run some quick to complete tests to detect significant breakages. For example, you have broken the URIs to essential resources. These are the smoke tests.
Regression tests run on every build and allow you to refactor effectively by catching what you break. Any kind of test can be regression test, but I find unit tests are most helpful finding the source of fault.
This should work:
input.*className*::-webkit-file-upload-button {
*style content..*
}
You want:
grep -A 5 '19:55' file
From man grep
:
Context Line Control
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a gup separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (described under --group-separator)
between contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.
With the -o or --only-matching option, this has no effect and a warning
is given.
--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).
--no-group-separator
Use empty string as a group separator.
"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".
Faster than rpm -qa | grep mysqld is:
which mysqld
in my case, the DefaultAppPool was stopped, I edited the Advanced Settings and set the value of Identity as LocalSystem, after that I start the DefaultAppPool.
1) Remember the main reason to separate .h and .cpp files is to hide the class implementation as a separately-compiled Obj code that can be linked to the user’s code that included a .h of the class.
2) Non-template classes have all variables concretely and specifically defined in .h and .cpp files. So the compiler will have the need information about all data types used in the class before compiling/translating ? generating the object/machine code Template classes have no information about the specific data type before the user of the class instantiate an object passing the required data type:
TClass<int> myObj;
3) Only after this instantiation, the complier generate the specific version of the template class to match the passed data type(s).
4) Therefore, .cpp Can NOT be compiled separately without knowing the users specific data type. So it has to stay as source code within “.h” until the user specify the required data type then, it can be generated to a specific data type then compiled
Here's an example of a person who wants to convert a blob to char(1000) with UTF-8 encoding:
CAST(a.ar_options AS CHAR(10000) CHARACTER SET utf8)
This is his answer. There is probably much more you can read about CAST right here. I hope it helps some.
Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity:
encodeURIComponent(str.replace(/&/g, "&"));
ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload
control to your page. Make sure it has all required attributes including ID
and runat
:
<asp:FileUpload ID="FileUpload1" runat="server" />
Instance of FileUpload1
will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
And that's it. All should work as expected.
The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))
You should have a look at moment
which is a python port of the excellent js lib momentjs
.
One advantage of it is the support of ISO 8601
strings formats, as well as a generic "% format" :
import moment
time_string='2012-10-09T19:00:55Z'
m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday
Result:
2012-10-09 19:10
2
This is the XML optional preamble.
version="1.0"
means that this is the XML standard this file conforms toencoding="utf-8"
means that the file is encoded using the UTF-8 Unicode encodingi realize it works after adding a slash behind like so
mysite/Controller/Action/21-9-2009 10:20/
I had the same issue where the softkeyboard was on top of the EditText views which were placed on the bottom of the screen. I was able to find a solution by adding a single line to my AndroidManifest.xml file's relevant activity.
android:windowSoftInputMode="adjustResize|stateHidden"
This is how the whole activity tag looks like:
<activity
android:name="com.my.MainActivity"
android:screenOrientation="portrait"
android:label="@string/title_activity_main"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
Here the most important value is the adjustResize. This will shift the whole UI up to give room for the softkeyboard.
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.
just excute the below command in terminal before running
open -a Simulator
REGEXP_COUNT should do the trick:
select REGEXP_COUNT('123-345-566', '-') from dual;
If you have HTML like this, for example:
<select id='myselect'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>
All you have to do is bind a function to the change
event of the select, and do what you need there:
<script type='text/javascript'>
$(function() {
$('#myselect').change(function() {
// if changed to, for example, the last option, then
// $(this).find('option:selected').text() == D
// $(this).val() == 4
// get whatever value you want into a variable
var x = $(this).val();
// and update the hidden input's value
$('#myhidden').val(x);
});
});
</script>
All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.
The best explanation is the GNU make manual itself: 4.6 Phony Targets section.
.PHONY
is one of make's Special Built-in Target Names. There are other targets that you may be interested in, so it's worth skimming through these references.
When it is time to consider a .PHONY target, make will run its recipe unconditionally, regardless of whether a file with that name exists or what its last-modification time is.
You may also be interested in make's Standard Targets such as all
and clean
.
Windows SendMessage API with send WM_KEYDOWN.
Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B
as a word character but #
as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a #
almost immediately and happily breaks there; whereas with the B
, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).
But that's pure speculation.
Just clear()
redundant fields.
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date truncatedDate = calendar.getTime();
From Java 8 a better option is to use truncatedTo
method of LocalDateTime
, e.g.:
LocalDateTime.now().truncatedTo(ChronoUnit.DAYS)
The best way to honestly do this is to change the number of columns you have instead of trying to bodge 5 into 12.
The best number you could probably use is 20 as it's divisble by 2, 4 & 5.
So in your variables.less
look for: @grid-columns: 12
and change this to 20
.
Then change your html to:
<div class="row">
<div class="col-xs-20">
<div class="col-xs-4" id="p1">One</div>
<div class="col-xs-4" id="p2">Two</div>
<div class="col-xs-4" id="p3">Three</div>
<div class="col-xs-4" id="p4">Four</div>
<div class="col-xs-4" id="p5">Five</div>
</div>
<!-- //col-lg-20 -->
</div>
I'd personally use display: flex
for this as bootstrap isn't designed greatly for a 5 column split.
The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET
parameter -
<script>
var a="Hello";
window.location.href = window.location.href+'?a='+a;
</script>
Your page will reload and now in your PHP, you'll have access to the $_GET['a']
variable.
<?php
$variable = $_GET['a'];
?>
The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:
scp [email protected]:/somedir/table /home/me/Desktop/.
The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.
If you are using Spring MVC, you can add following mvn tag to exclude resources file from Spring Dispatch Servlet
<mvc:resources mapping="/js/*.js" location="/js/"/>
<mvc:resources mapping="/css/*.css" location="/css/"/>
<mvc:resources mapping="/images/*.*" location="/images/"/>
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.
Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.
use kubeadm reset
command. this will un-configure the kubernetes cluster.
As noted by S.Lott,
Variable set outside init belong to the class. They're shared by all instances.
Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.
However, Note that class variables can be accessed via self.<var> until they are masked by an object variable with a similar name This means that reading self.<var> before assigning it a value will return the value of Class.<var> but afterwards it will return obj.<var> . Here is an example
In [20]: class MyClass:
...: elem = 123
...:
...: def update(self,i):
...: self.elem=i
...: def print(self):
...: print (MyClass.elem, self.elem)
...:
...: c1 = MyClass()
...: c2 = MyClass()
...: c1.print()
...: c2.print()
123 123
123 123
In [21]: c1.update(1)
...: c2.update(42)
...: c1.print()
...: c2.print()
123 1
123 42
In [22]: MyClass.elem=22
...: c1.print()
...: c2.print()
22 1
22 42
Second note: Consider slots. They may offer a better way to implement object variables.
Have you tried using Html.fromHtml(source)?
I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.
Swift 5.
To convert a String
to a URL
:
let stringToURL = URL(string: "your-string")
To convert a URL
to a String
:
let urlToString = stringToURL?.absoluteString
"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t
The simple example of using a property in an interface:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
Here is a much-expanded version of Simon Hewitt's class:
/// <summary>
/// Safely converts a <see cref="float"/> to an <see cref="int"/> for floating-point comparisons.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct FloatToInt : IEquatable<FloatToInt>, IEquatable<float>, IEquatable<int>, IComparable<FloatToInt>, IComparable<float>, IComparable<int>
{
/// <summary>
/// Initializes a new instance of the <see cref="FloatToInt"/> class.
/// </summary>
/// <param name="floatValue">The <see cref="float"/> value to be converted to an <see cref="int"/>.</param>
public FloatToInt(float floatValue)
: this()
{
FloatValue = floatValue;
}
/// <summary>
/// Gets the floating-point value as an integer.
/// </summary>
[FieldOffset(0)]
public readonly int IntValue;
/// <summary>
/// Gets the floating-point value.
/// </summary>
[FieldOffset(0)]
public readonly float FloatValue;
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(FloatToInt other)
{
return other.IntValue == IntValue;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(float other)
{
return IntValue == new FloatToInt(other).IntValue;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(int other)
{
return IntValue == other;
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(FloatToInt other)
{
return IntValue.CompareTo(other.IntValue);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(float other)
{
return IntValue.CompareTo(new FloatToInt(other).IntValue);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(int other)
{
return IntValue.CompareTo(other);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <returns>
/// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
/// <param name="obj">Another object to compare to. </param><filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (obj.GetType() != typeof(FloatToInt))
{
return false;
}
return Equals((FloatToInt)obj);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
return IntValue;
}
/// <summary>
/// Implicitly converts from a <see cref="FloatToInt"/> to an <see cref="int"/>.
/// </summary>
/// <param name="value">A <see cref="FloatToInt"/>.</param>
/// <returns>An integer representation of the floating-point value.</returns>
public static implicit operator int(FloatToInt value)
{
return value.IntValue;
}
/// <summary>
/// Implicitly converts from a <see cref="FloatToInt"/> to a <see cref="float"/>.
/// </summary>
/// <param name="value">A <see cref="FloatToInt"/>.</param>
/// <returns>The floating-point value.</returns>
public static implicit operator float(FloatToInt value)
{
return value.FloatValue;
}
/// <summary>
/// Determines if two <see cref="FloatToInt"/> instances have the same integer representation.
/// </summary>
/// <param name="left">A <see cref="FloatToInt"/>.</param>
/// <param name="right">A <see cref="FloatToInt"/>.</param>
/// <returns>true if the two <see cref="FloatToInt"/> have the same integer representation; otherwise, false.</returns>
public static bool operator ==(FloatToInt left, FloatToInt right)
{
return left.IntValue == right.IntValue;
}
/// <summary>
/// Determines if two <see cref="FloatToInt"/> instances have different integer representations.
/// </summary>
/// <param name="left">A <see cref="FloatToInt"/>.</param>
/// <param name="right">A <see cref="FloatToInt"/>.</param>
/// <returns>true if the two <see cref="FloatToInt"/> have different integer representations; otherwise, false.</returns>
public static bool operator !=(FloatToInt left, FloatToInt right)
{
return !(left == right);
}
}
$('input:radio[name="postage"]').change(function(){
if($(this).val() === 'Yes'){
// append stuff
}
});
This will listen for a change event on the radio buttons. At the time the user clicks Yes
, the event will fire and you will be able to append anything you like to the DOM.
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
.button input,
.button a {
...
}
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
Try this
alter table TableName
add constraint df_ConstraintNAme
default getutcdate() for [Date]
example
create table bla (id int)
alter table bla add constraint dt_bla default 1 for id
insert bla default values
select * from bla
also make sure you name the default constraint..it will be a pain in the neck to drop it later because it will have one of those crazy system generated names...see also How To Name Default Constraints And How To Drop Default Constraint Without A Name In SQL Server
You should try this one:
Console.WriteLine("{0}.{1}.{2}", mon, da, yet);
See http://www.dotnetperls.com/console-writeline for more details.
As others have said, it is not possible to directly lookup a parent from a nested child. All of the proposed solutions advise various different ways of referring back to the parent object or parent scope through an explicit variable name.
However, directly traversing up to the the parent object is possible if you employ recursive ES6 Proxies on the parent object.
I've written a library called ObservableSlim that, among other things, allows you to traverse up from a child object to the parent.
Here's a simple example (jsFiddle demo):
var test = {"hello":{"foo":{"bar":"world"}}};
var proxy = ObservableSlim.create(test, true, function() { return false });
function traverseUp(childObj) {
console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {"foo":{"bar":"world"}}
console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object
};
traverseUp(proxy.hello.foo);
I have used ndk.dir=/usr/shareData/android-ndk-r11b
// path of ndk
in local.properties file in android studio project. and
add this line :
android.useDeprecatedNdk=true
in gradle.properties file in android studio project.
More information here: http://tools.android.com/tech-docs/android-ndk-preview
To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
Have you tried simply using the media attribute for you css reference?
<link rel="stylesheet" href="css/style2.css" media="print" type="text/css" />
Or set it to screen if you don't want the printed version to use the style:
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
This way you don't need to add it dynamically.
Use +
, the string concatenation operator:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);
or use String.valueOf(int)
:
ed.setText(String.valueOf(x));
or use Integer.toString(int)
:
ed.setText(Integer.toString(x));
You could also create a new DevicePolicyManager and then use removeAdmin(adminReceiver) from an onClickListener of a button in your app
//set the onClickListener here
{
ComponentName devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
DevicePolicyManager dpm = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
dpm.removeActiveAdmin(devAdminReceiver);
}
And then you can uninstall
I found, bizarrely, that I could fix the errors by placing the timezone declaration at the TOP of my php.ini file.
It was already in my php.ini. Twice, actually. And I was pulling my hair out because everyone was saying there must be another ini being loaded... There wasn't.
Hope this can save someone else the time/hair loss.
Use ORACLE equivalent of getdate()
which is sysdate
. Read about here.
Getdate() belongs to SQL Server , will not work on Oracle.
Other option is current_date
It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.
Your /usr/local/bin/groovy
is a shell script wrapping the Java runtime running Groovy.
See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).
final Properties properties = new Properties();
try (final InputStream stream =
this.getClass().getResourceAsStream("foo.properties")) {
properties.load(stream);
/* or properties.loadFromXML(...) */
}
You can use sed
for this too -
sed -n '320123'p filename
This will print line number 320123.
If you want a range then you can do -
sed -n '320123,320150'p filename
If you want from a particular line to the very end then -
sed -n '320123,$'p filename
The correct way to change the default primary colour in Bootstrap 4.x using SASS, or any other colours like secondary, success and so on.
Create the following SASS file and import Bootstrap SASS as indicated:
// (Required) Import Bootstrap
@import "bootstrap/functions";
@import "bootstrap/variables";
@import "bootstrap/mixins";
$primary: blue;
$secondary: green;
$my-color: red;
$theme-colors: (
primary: $primary,
secondary: $secondary,
my-color: $my-color
);
// Add below your SASS or CSS code
// (Required) Import Bootstrap
@import "bootstrap/bootstrap";
Run installer in command line (Admin) with argument:
vs_community_ENU.exe /uninstall /force
Then:
vs_community_ENU /CustomInstallPath E:\VisualStudio2015
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
I would say that using:
* {
margin: 0;
padding: 0;
}
is a bad way of solving this.
The reason for the h1 margin popping out of the parent is that the parent does not have a padding.
If you add a padding to the parent element of the h1, the margin will be inside the parent.
Resetting all paddings and margins to 0 can cause a lot of side effects. Then it's better to remove margin-top for this specific headline.
You could try something like this using approach for How to find the last field using 'cut':
Explanation
rev
reverses /home/user/mydir/file_name.c
to be c.eman_elif/ridym/resu/emoh/
cut
uses dot (ie /
) as the delimiter, and chooses the first field, which is c.eman_elif
file_name.c
$ VAR="/home/user/mydir/file_name.c"
$ echo $VAR | rev | cut -f1 -d"/" | rev
file_name.c
Per the jQuery documentation, try this:
$('input[inputName\\[\\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
$('input[name="inputName[]"][value="someValue"]')
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime
using System.setProperty(String key, String value)
or via the various
System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
.
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc,
and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count())
, like this:
session.query(MyModel).with_entities(func.count()).scalar()
It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities
after joins, otherwise SQLAlchemy could raise the Don't know how to join
error.
For example:
User
model (id
, name
) and Song
model (id
, title
, genre
)UserSong
model (user_id
, song_id
, is_liked
) where user_id
+ song_id
is a primary key)We want to get a number of user's liked rock songs:
SELECT count(*)
FROM user_song
JOIN song ON user_song.song_id = song.id
WHERE user_song.user_id = %(user_id)
AND user_song.is_liked IS 1
AND song.genre = 'rock'
This query can be generated in a following way:
user_id = 1
query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
and_(
UserSong.user_id == user_id,
UserSong.is_liked.is_(True),
Song.genre == 'rock'
)
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()
Complete example is here.
The normal way to control this is with git config
For example
git config --global core.autocrlf true
For details, scroll down in this link to Pro Git to the section named "core.autocrlf"
If you want to know what file this is saved in, you can run the command:
git config --global --edit
and the git global config file should open in a text editor, and you can see where that file was loaded from.
I'd implement this to return a boolean:
function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
It'll work on both unsigned and signed numbers. When the modulus return -1
or 1
it'll get translated to true
.
Non-modulus solution:
var is_finite = isFinite;
var is_nan = isNaN;
function isOdd (discriminant) {
if (is_nan(discriminant) && !is_finite(discriminant)) {
return false;
}
// Unsigned numbers
if (discriminant >= 0) {
while (discriminant >= 1) discriminant -= 2;
// Signed numbers
} else {
if (discriminant === -1) return true;
while (discriminant <= -1) discriminant += 2;
}
return !!discriminant;
}
I extends the SimpleJpaRepository:
public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
implements ExtendedRepository<T> {
private final JpaEntityInformation<T, ?> entityInformation;
private final EntityManager em;
public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
final EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityInformation = entityInformation;
this.em = entityManager;
}
}
and adds this class to @EnableJpaRepositoryries repositoryBaseClass.
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single user,
| and is normally provided in ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all Maven
| users on a machine (assuming they're all using the same Maven
| installation). It's normally provided in
| ${maven.conf}/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start at
| getting the most out of your Maven installation. Where appropriate, the default
| values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ${user.home}/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set to false,
| maven will use a sensible default value, perhaps based on some other setting, for
| the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when executing a build.
| This will have an effect on artifact downloads, artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
| when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to the network.
| Unless otherwise specified (by system property or command-line switch), the first proxy
| specification in this list marked as active will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>false</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used within the system.
| Authentication profiles can be used whenever maven must make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a particular server, identified by
| a unique name within the system (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
| used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote repositories.
|
| It works like this: a POM may declare a repository to use in resolving certain artifacts.
| However, this repository may have problems with heavy traffic at times, so people have mirrored
| it to several places.
|
| That repository definition will have a unique id, so we can create a mirror reference for that
| repository, to be used as an alternate download site. The mirror site will be the preferred
| server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
</mirrors>
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways, and which can modify
| the build process. Profiles provided in the settings.xml are intended to provide local machine-
| specific paths and repository locations which allow the build to work in the local environment.
|
| For example, if you have an integration testing plugin - like cactus - that needs to know where
| your Tomcat instance is installed, you can provide a variable here such that the variable is
| dereferenced during the build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
| section of this document (settings.xml) - will be discussed later. Another way essentially
| relies on the detection of a system property, either matching a particular value for the property,
| or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
| value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
| Finally, the list of active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
| repositories, plugin repositories, and free-form properties to be used as configuration
| variables for plugins in the POM.
|
|-->
<profiles>
<profile>
<id>maven-https</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>central</id>
<url>https://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>https://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
<!-- profile
| Specifies a set of introductions to the build process, to be activated using one or more of the
| mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
| or the command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a consistent naming convention
| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
| This will make it more intuitive to understand what the set of introduced profiles is attempting
| to accomplish, particularly when you only have a list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
<!--
| Here is another profile, activated by the system property 'target-env' with a value of 'dev',
| which provides a specific path to the Tomcat instance. To use this, your plugin configuration
| might hypothetically look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
| anything, you could just leave off the <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.
The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.
What about .GlobalEnv$a <- "new"
? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign()
function.
maxRequestLength (length in KB) Here as ex. I took 1024 (1MB) maxAllowedContentLength (length in Bytes) should be same as your maxRequestLength (1048576 bytes = 1MB).
<system.web>
<httpRuntime maxRequestLength="1024" executionTimeout="3600" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576"/>
</requestFiltering>
</security>
</system.webServer>
No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.
If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.
Just use awk, it's much simpler than grep in letting you clearly express compound conditions.
If you want to skip lines that contains both loom
and gloom
:
awk '/loom/ && !/gloom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
or if you want to print them:
awk '/(^|[^g])loom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
and if the reality is you just want lines where loom
appears as a word by itself:
awk '/\<loom\>/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)
I had a requirement to take values from text file and use as key value pair. i have content in text file as key = value, so i have used split method with separator as "=" and wrote below code
d = {}
file = open("filename.txt")
for x in file:
f = x.split("=")
d.update({f[0].strip(): f[1].strip()})
By using strip method any spaces before or after the "=" separator are removed and you will have the expected data in dictionary format
If chmod not working then you also try
import os
os.system('sh script.sh')
#you can also use bash instead of sh
test by me thanks
For n
number of inputs declare the variable as an empty list and use the same syntax to proceed:
>>> x=input('Enter value of a and b').split(",")
Enter value of a and b
1,2,3,4
>>> x
['1', '2', '3', '4']
This is not an answer to the OP question but a toy example to illustrate the answer of @ShikharDua above which I found very useful.
While this fragment is trivial, in the actual data I had 1,000s of rows, and many columns, and I wished to be able to group by different columns and then perform the stats below for more than one taget column. So having a reliable method for building the data frame one row at a time was a great convenience. Thank you @ShikharDua !
import pandas as pd
BaseData = pd.DataFrame({ 'Customer' : ['Acme','Mega','Acme','Acme','Mega','Acme'],
'Territory' : ['West','East','South','West','East','South'],
'Product' : ['Econ','Luxe','Econ','Std','Std','Econ']})
BaseData
columns = ['Customer','Num Unique Products', 'List Unique Products']
rows_list=[]
for name, group in BaseData.groupby('Customer'):
RecordtoAdd={} #initialise an empty dict
RecordtoAdd.update({'Customer' : name}) #
RecordtoAdd.update({'Num Unique Products' : len(pd.unique(group['Product']))})
RecordtoAdd.update({'List Unique Products' : pd.unique(group['Product'])})
rows_list.append(RecordtoAdd)
AnalysedData = pd.DataFrame(rows_list)
print('Base Data : \n',BaseData,'\n\n Analysed Data : \n',AnalysedData)
If you're looking for the equivalent of PHP's empty
function, check this out:
function empty(mixed_var) {
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty({'aFunc' : function () { alert('humpty'); } });
// returns 5: false
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixed_var === emptyValues[i]) {
return true;
}
}
if (typeof mixed_var === 'object') {
for (key in mixed_var) {
// TODO: should we check for own properties only?
//if (mixed_var.hasOwnProperty(key)) {
return false;
//}
}
return true;
}
return false;
}
To check for all int chars, you can simply use a double negative. if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
Just another way to use Git's awesomeness...
git difftool HEAD HEAD@{N} /PATH/FILE.ext
sudo apt-get install build-essential
is enough to get it working.
Use this:
In [105]: a
Out[105]:
array([[15, 30, 88, 31, 33],
[53, 38, 54, 47, 56],
[67, 2, 74, 10, 16],
[86, 33, 15, 51, 32],
[32, 47, 76, 15, 81]], dtype=int32)
In [106]: float32(a)
Out[106]:
array([[ 15., 30., 88., 31., 33.],
[ 53., 38., 54., 47., 56.],
[ 67., 2., 74., 10., 16.],
[ 86., 33., 15., 51., 32.],
[ 32., 47., 76., 15., 81.]], dtype=float32)
I am following the solution given by slebetman (go read it for all the details), but adjusted, since your object is non-nested.
// First create the array of keys/values so that we can sort it:
var sort_array = [];
for (var key in list) {
sort_array.push({key:key,value:list[key]});
}
// Now sort it:
sort_array.sort(function(x,y){return x.value - y.value});
// Now process that object with it:
for (var i=0;i<sort_array.length;i++) {
var item = list[sort_array[i].key];
// now do stuff with each item
}
I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.
IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.
If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.
I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:
String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.com/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time,
We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'
"%x" instead of "%Y%m%d-%H%M%S"
As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.
Sample implementation using WatiN:
class FacebookUser
{
public string Name { get; set; }
public long Id { get; set; }
}
public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
var users = new List<FacebookUser>();
Settings.Instance.MakeNewIeInstanceVisible = false;
using (var browser = new IE("https://www.facebook.com"))
{
try
{
browser.TextField(Find.ByName("email")).Value = email;
browser.TextField(Find.ByName("pass")).Value = password;
browser.Form(Find.ById("login_form")).Submit();
browser.WaitForComplete();
}
catch (ElementNotFoundException)
{
// We're already logged in
}
browser.GoTo("https://www.facebook.com/friends");
var watch = new Stopwatch();
watch.Start();
Link previousLastLink = null;
while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
{
var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).LastOrDefault();
if (lastLink == null || previousLastLink == lastLink)
{
break;
}
var ieElement = lastLink.NativeElement as IEElement;
if (ieElement != null)
{
var htmlElement = ieElement.AsHtmlElement;
htmlElement.scrollIntoView();
browser.WaitForComplete();
}
previousLastLink = lastLink;
}
var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).ToList();
var idRegex = new Regex("id=(?<id>([0-9]+))");
foreach (var link in links)
{
string hovercard = link.GetAttributeValue("data-hovercard");
var match = idRegex.Match(hovercard);
long id = 0;
if (match.Success)
{
id = long.Parse(match.Groups["id"].Value);
}
users.Add(new FacebookUser
{
Name = link.Text,
Id = id
});
}
}
return users;
}
Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.
1) Constant Pointers : These type of pointers are the one which cannot change address they are pointing to. This means that suppose there is a pointer which points to a variable (or stores the address of that variable). Now if we try to point the pointer to some other variable (or try to make the pointer store address of some other variable), then constant pointers are incapable of this.
A constant pointer is declared as : int *const ptr
( the location of 'const' make the pointer 'ptr' as constant pointer)
2) Pointer to Constant : These type of pointers are the one which cannot change the value they are pointing to. This means they cannot change the value of the variable whose address they are holding.
A pointer to a constant is declared as : const int *ptr
(the location of 'const' makes the pointer 'ptr' as a pointer to constant.
Example
Constant Pointer
#include<stdio.h>
int main(void)
{
int a[] = {10,11};
int* const ptr = a;
*ptr = 11;
printf("\n value at ptr is : [%d]\n",*ptr);
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
ptr++;
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
return 0;
}
Now, when we compile the above code, compiler complains :
practice # gcc -Wall constant_pointer.c -o constant_pointer
constant_pointer.c: In function ‘main’:
constant_pointer.c:13: error: increment of read-only variable ‘ptr’
Hence we see very clearly above that compiler complains that we cannot changes the address held by a constant pointer.
Pointer to Constants
#include<stdio.h>
int main(void)
{
int a = 10;
const int* ptr = &a;
printf("\n value at ptr is : [%d]\n",*ptr);
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
*ptr = 11;
return 0;
}
Now, when the above code is compiled, the compiler complains :
practice # gcc -Wall pointer_to_constant.c -o pointer_to_constant
pointer_to_constant.c: In function ‘main’:
pointer_to_constant.c:12: error: assignment of read-only location ‘*ptr’
Hence here too we see that compiler does not allow the pointer to a constant to change the value of the variable being pointed.
Should be pretty straightforward, its just the reverse of your previous method;
public static int GetEnumFromDescription(string description, Type enumType)
{
foreach (var field in enumType.GetFields())
{
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
if(attribute == null)
continue;
if(attribute.Description == description)
{
return (int) field.GetValue(null);
}
}
return 0;
}
Usage:
Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));
for the whole question:
cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.
Run the above with the cron every hour, or
while :
do
cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
sleep 3600
done
How to build an image with custom name without using yml file:
docker build -t image_name .
How to run a container with custom name:
docker run -d --name container_name image_name
a
is defined locally in the function, and can't be used outside the function. If you want to return a char
array from the function, you'll need to allocate it dynamically:
char *a = malloc(1000);
And at some point call free
on the returned pointer.
You should also see a warning at this line: char b = "blah";
: you're trying to assign a string literal to a char
.
It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send
in your each REST block...
So you can do something like this as a simple next()
example:
app.get("/", (req, res, next) => {
console.log("req:", req, "res:", res);
res.send(["data": "whatever"]);
next();
},(req, res) =>
console.log("it's all done!");
);
It's also very useful when you'd like to have a middleware in your app...
To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
})
app.listen(3000);
here is a simply smart code :
function generate(l) {
if (typeof l==='undefined'){var l=8;}
/* c : alphanumeric character string */
var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
n=c.length,
/* p : special character string */
p='!@#$+-*&_',
o=p.length,
r='',
n=c.length,
/* s : determinate the position of the special character */
s=Math.floor(Math.random() * (p.length-1));
for(var i=0; i<l; ++i){
if(s == i){
/* special charact insertion (random position s) */
r += p.charAt(Math.floor(Math.random() * o));
}else{
/* alphanumeric insertion */
r += c.charAt(Math.floor(Math.random() * n));
}
}
return r;
}
Simply call generate(), and it do key containing one special character (!@#$+-*&_) for security.
Possible results : WJGUk$Ey, gaV7#fF7, ty_T55DD, YtrQMWveZqYyYKo_
There is more details and example in my website : https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/
There is a DateTimePicker
available in the Extended Toolkit.
Here is a tidyverse
option that might work depending on the data, and some caveats on its usage:
library(tidyverse)
starting_df %>%
rownames_to_column() %>%
gather(variable, value, -rowname) %>%
spread(rowname, value)
rownames_to_column()
is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column()
and replace rowname
with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths
sample data would be:
smiths %>%
gather(variable, value, -subject) %>%
spread(subject, value)
Using the example starting_df
with the tidyverse
approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths
data will not give that warning because all columns except for subject
are doubles.
The earlier answer using as.data.frame(t())
will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE
is added,
whereas the tidyverse
option converts everything to a character by default if
there are mixed column types.
UPDATE
Now it's easier than ever (Angular 1.3), just add a debounce option on the model.
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
Updated plunker:
http://plnkr.co/edit/4V13gK
Documentation on ngModelOptions:
https://docs.angularjs.org/api/ng/directive/ngModelOptions
Old method:
Here's another method with no dependencies beyond angular itself.
You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.
$scope.$watch('searchStr', function (tmpStr)
{
if (!tmpStr || tmpStr.length == 0)
return 0;
$timeout(function() {
// if searchStr is still the same..
// go ahead and retrieve the data
if (tmpStr === $scope.searchStr)
{
$http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
// update the textarea
$scope.responseData = data.res;
});
}
}, 1000);
});
and this goes into your view:
<input type="text" data-ng-model="searchStr">
<textarea> {{responseData}} </textarea>
The mandatory plunker: http://plnkr.co/dAPmwf
Windows 10 Defender Firewall was blocking it. I turned it off, ran the mvc core 2.0 application, and it worked. I then turned windows firewall on again and it remained working. All the other solutions although well intended didn't work for me. Hope this helps someone out there.
To change tab settings, click the text area right to the Ln/Col text in the status bar on the bottom right of vscode window.
The name can be Tab Size
or Spaces
.
A menu will pop up with all available actions and settings.
/* =============================
* Disable / Enable Page Scroll
* when Bootstrap Modals are
* shown / hidden
* ============================= */
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function theMouseWheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', theMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = theMouseWheel;
}
function enable_scroll() {
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', theMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = null;
}
$(function () {
// disable page scrolling when modal is shown
$(".modal").on('show', function () { disable_scroll(); });
// enable page scrolling when modal is hidden
$(".modal").on('hide', function () { enable_scroll(); });
});
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:
action="javascript:checkout()"
You try this?
Don't forget include the script reference in the html head.
I don't know cause of that works in firefox. Regards.
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
Java is the language and includes a strict and strongly typed syntax with which you should be very familiar by now.
Java 2 Platform, Standard Edition, also known as J2SE, referred to the platform and included the classes in the java.lang and java.io packages, among others. It was the building block that Java applications were built upon.
A Java Virtual Machine, or JVM, is a software virtual machine that runs compiled Java code. Because compiled Java code is merely bytecode, the JVM is responsible for compiling that bytecode to machine code before running it. (This is often called the Just In Time Compiler or JIT Compiler.) The JVM also takes care of memory management so that application code doesn’t have to.
The Java Development Kit, or JDK, was and remains the piece of software Java developers use to create Java applications. It contains a Java language compiler, a documentation generator, tools for working with native code, and (typically) the Java source code for the platform to enable debugging platform classes.
The Java Runtime Environment, or JRE, was and remains the piece of software end users download to run compiled Java applications. It includes a JVM but does not contain any of the development tools bundled in the JDK. The JDK, however, does contain a JRE.
Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,
In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter
command.
x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]
# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
cols=[]
for l in lst:
if l=='A':
cols.append('red')
elif l=='B':
cols.append('blue')
else:
cols.append('green')
return cols
# Create the colors list using the function above
cols=pltcolor(x)
plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()
Check my sample solution
<h5 style="float: left; width: 50%;">Employee: Employee Name</h5>
<h5 style="float: right; width: 50%; text-align: right;">Employee: Employee Name</h5>
This will divide your page into two and insert the two header elements to the right and left part equally.
What I usually do is use clock()
or time()
from the time
library. clock
measures interpreter time, while time
measures system time. Additional caveats can be found in the docs.
For example,
def fn():
st = time()
dostuff()
print 'fn took %.2f seconds' % (time() - st)
Or alternatively, you can use timeit
. I often use the time
approach due to how fast I can bang it out, but if you're timing an isolate-able piece of code, timeit
comes in handy.
From the timeit docs,
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Then to convert to minutes, you can simply divide by 60. If you want the script runtime in an easily readable format, whether it's seconds or days, you can convert to a timedelta
and str
it:
runtime = time() - st
print 'runtime:', timedelta(seconds=runtime)
and that'll print out something of the form [D day[s], ][H]H:MM:SS[.UUUUUU]
. You can check out the timedelta docs.
And finally, if what you're actually after is profiling your code, Python makes available the profile library as well.
For example string s="(U+007c)"
To remove only the parentheses from s, try the below one:
import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)
I've tried bson = require('../browser_build/bson');
but end up running into another error
Cannot set property 'BSON_BINARY_SUBTYPE_DEFAULT' of undefined
Finally I fixed this issue simply by npm update
, this will fix the bson module in mongoose.
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Gives a tuple of lists as in the question.
list1, list2 = [list(tup) for tup in zip(*original)]
Unpacks the two lists.
If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:
type User = {
Username?: string;
Email?: string;
}
I use it in a practical sense when we transfer large binary objects (images) via web services. So when I am testing a C# web service using a python script, the binary object can be recreated with a little magic.
[In python]
import base64
imageAsBytes = base64.b64decode( dataFromWS )
The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):
mWebView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}
});
mWebView.loadUrl(url);
Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.
You need to define the enum outside of the class.
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
// ...
That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.
Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.
An example:
try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}
You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)
NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.
OLD VERSION: https://jsbin.com/mahenes/edit?js,output
Also, here is a modified version (can someone test on mac and confirm)
NEW VERSION: https://jsbin.com/xiconuv/edit?js,output
NEW VERSION:
function isCapslock(e) {
const IS_MAC = /Mac/.test(navigator.platform);
const charCode = e.charCode;
const shiftKey = e.shiftKey;
if (charCode >= 97 && charCode <= 122) {
capsLock = shiftKey;
} else if (charCode >= 65 && charCode <= 90
&& !(shiftKey && IS_MAC)) {
capsLock = !shiftKey;
}
return capsLock;
}
OLD VERSION:
function isCapslock(e) {
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}
For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...
uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'
The above keys are just sample representation.
In addition to the accepted answer, there's a third option that can be useful in some cases:
You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.
First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:
from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes # py3 only
def uuid1mc():
# NOTE: The constant here is required by the UUIDv1 spec...
return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)
(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)
In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random
module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.
import random
from uuid import uuid1
def uuid1mc_insecure():
return uuid1(random.getrandbits(48) | 0x010000000000)
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
As a side answer it's worth to note that:
aria-hidden
or aria-expanded
. But only if implemented and tested properly!maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
Alternatively we can use lxml, it support xpath and very fast!
from lxml import html, etree
attr = html.fromstring(html_text)#passing the raw html
handles = attr.xpath('//div[@class="stylelistrow"]')#xpath exresssion to find that specific class
for each in handles:
print(etree.tostring(each))#printing the html as string
For loops are a bad construct for this.
while
var numbers = new List<int>(Enumerable.Range(1, 3));
while (numbers.Count > 0)
{
numbers.RemoveAt(0);
}
But, if you absolutely must use for
var numbers = new List<int>(Enumerable.Range(1, 3));
for (; numbers.Count > 0;)
{
numbers.RemoveAt(0);
}
Or, this:
public static class Extensions
{
public static IList<T> Remove<T>(
this IList<T> numbers,
Func<T, bool> predicate)
{
numbers.ForEachBackwards(predicate, (n, index) => numbers.RemoveAt(index));
return numbers;
}
public static void ForEachBackwards<T>(
this IList<T> numbers,
Func<T, bool> predicate,
Action<T, int> action)
{
for (var i = numbers.Count - 1; i >= 0; i--)
{
if (predicate(numbers[i]))
{
action(numbers[i], i);
}
}
}
}
Usage:
var numbers = new List<int>(Enumerable.Range(1, 10)).Remove((n) => n > 5);
A sample .gitignore file can look like one below for a Android Studio project
# built application files
*.apk
*.ap_
# files for the dex VM
*.dex
# Java class files
*.class
# generated files
bin/
gen/
# Local configuration file (sdk path, etc)
local.properties
#Eclipse
*.pydevproject
.project
.metadata
bin/**
tmp/**
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
YourProjetcName/.gradle/
YourProjetcName/app/build/
*/YourProjetcName/.gradle/
*/YourProjetcName/app/build/
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
# Proguard folder generated by Eclipse
proguard/
# Intellij project files
*.iml
*.ipr
*.iws
.idea/
/build
build/
*/build/
*/*/build/
*/*/*/build/
*.bin
*.lock
YourProjetcName/app/build/
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
.gradle/
app/build/
*app/build/
# Local configuration file (sdk path, etc)
local.properties
/YourProjetcName/build/intermediates/lint-cache/api-versions-6-23.1.bin
appcompat_v7_23_1_1.xml
projectFilesBackup
build.gradle
YourProjetcName.iml
YourProjetcName.iml
gradlew
gradlew.bat
local.properties
settings.gradle
.gradle
.idea
android
build
gradle
Right, but as long as you use ASCII characters even a multibyte character set would still give a limitation of exactly 30 characters... so unless you want to put hearts and smiling cats in you're DB names your fine...
If you use Virtual Box you can connect Mac OSX (and I think Linux) to your virtual windows machine using one line of code --> I suggest stopping the box before running this in terminal.
VBoxManage modifyvm "YOUR VM NAME" --natdnshostresolver1 on
I will note that this is from the Dinghy docs, which I am running, but its a virtual box command so it shouldn't actually care what you use as long as its Virtual Box
Dont forget the "BUTTON" element wich can handle some more HTML inside...
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
There are many good answers, but I would use StringUtils
from commons-lang. I find StringUtils.substringBefore()
more readable than the alternatives:
String result = StringUtils.substringBefore("34.1 -118.33\n<!--ABCDEFG-->", "\n");
In my experience with regex you really need to focus on what EXACTLY you are trying to match, rather than what NOT to match.
for example
\d{2}
[1-9][0-9]
The first expression will match any 2 digits....and the second will match 1 digit from 1 to 9 and 1 digit - any digit. So if you type 07 the first expression will validate it, but the second one will not.
See this for advanced reference:
http://www.regular-expressions.info/refadv.html
EDITED:
^((?!my string).)*$
Is the regular expression for does not contain "my string".
With Java 8
, allow you doing something more elegant like this:
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length
If you are using java8 :
java.time.Year.of(year).isLeap()
Java implementation of above method:
public static boolean isLeap(long year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
Try the following approach:
AutoClosingMessageBox.Show("Text", "Caption", 1000);
Where the AutoClosingMessageBox
class implemented as following:
public class AutoClosingMessageBox {
System.Threading.Timer _timeoutTimer;
string _caption;
AutoClosingMessageBox(string text, string caption, int timeout) {
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
using(_timeoutTimer)
MessageBox.Show(text, caption);
}
public static void Show(string text, string caption, int timeout) {
new AutoClosingMessageBox(text, caption, timeout);
}
void OnTimerElapsed(object state) {
IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
if(mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
}
const int WM_CLOSE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
Update: If you want to get the return value of the underlying MessageBox when user selects something before the timeout you can use the following version of this code:
var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);
if(userResult == System.Windows.Forms.DialogResult.Yes) {
// do something
}
...
public class AutoClosingMessageBox {
System.Threading.Timer _timeoutTimer;
string _caption;
DialogResult _result;
DialogResult _timerResult;
AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
_timerResult = timerResult;
using(_timeoutTimer)
_result = MessageBox.Show(text, caption, buttons);
}
public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
}
void OnTimerElapsed(object state) {
IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
if(mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
_result = _timerResult;
}
const int WM_CLOSE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
Yet another Update
I have checked the @Jack's case with YesNo
buttons and discovered that the approach with sending the WM_CLOSE
message does not work at all.
I will provide a fix in the context of the separate AutoclosingMessageBox library. This library contains redesigned approach and, I believe, can be useful to someone.
It also available via NuGet package:
Install-Package AutoClosingMessageBox
Release Notes (v1.0.0.2):
- New Show(IWin32Owner) API to support most popular scenarios (in the
context of #1 );
- New Factory() API to provide full control on MessageBox showing;
The print function in python adds itself \n
You could use
import sys
sys.stdout.write(a)
instead
onActivityResult() of MAinActivity will call , onActivityResult() of Fragement wont call because fragment is placed in Activity so obviously it come back to MainActivity
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
This method orderBy
does not change the input array,
you have to assign the result to your array :
var chars = this.state.characters;
chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
this.setState({characters: chars})
Although you can use the
{{ game.gameDate|date('Y-m-d') }}
approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime
class, and adding a __toString()
method to it that checks the locale and acts accordingly.
Edit:
As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate
filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime
.
If the program won't work without the files it seems like splitting them into a separate repo is a bad idea. We have large test suites that we break into a separate repo but those are truly "auxiliary" files.
However, you may be able to manage the files in a separate repo and then use git-submodule
to pull them into your project in a sane way. So, you'd still have the full history of all your source but, as I understand it, you'd only have the one relevant revision of your images submodule. The git-submodule
facility should help you keep the correct version of the code in line with the correct version of the images.
Here's a good introduction to submodules from Git Book.
os.getenv('HOSTNAME')
and os.environ['HOSTNAME']
don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:
import socket
socket.gethostbyaddr(socket.gethostname())[0]
It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.
If you defined an alias in /etc/hosts then socket.gethostname()
will return the alias. platform.uname()[1]
does the same thing.
I ran into a case where the above didn't work. This is what I'm using now:
import socket
if socket.gethostname().find('.')>=0:
name=socket.gethostname()
else:
name=socket.gethostbyaddr(socket.gethostname())[0]
It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.
If you are using Git GUI, first fetch then merge.
Fetch via Remote menu >> Fetch >> Origin. Merge via Merge menu >> Merge Local.
The following dialog appears.
Select the tracking branch radio button (also by default selected), leave the yellow box empty and press merge and this should update the files.
I had already reverted some local changes before doing these steps since I wanted to discard those anyways so I don't have to eliminate via merge later.
If the divs are hidden, they will never trigger the mouseover
event.
You will have to listen to the event of some other unhidden element.
You can consider wrapping your hidden divs into container divs that remain visible, and then act on the mouseover
event of these containers.
<div style="width: 80px; height: 20px; background-color: red;" _x000D_
onmouseover="document.getElementById('div1').style.display = 'block';">_x000D_
<div id="div1" style="display: none;">Text</div>_x000D_
</div>
_x000D_
You could also listen for the mouseout
event if you want the div to disappear when the mouse leaves the container div:
onmouseout="document.getElementById('div1').style.display = 'none';"
#!/bin/bash
IFS=$'\n' read -d'' -r -a inlines < testinput
IFS=$'\n' read -d'' -r -a outlines < testoutput
counter=0
cat testinput | while read line;
do
echo "$((${inlines[$counter]}-${outlines[$counter]}))"
counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline;
do
echo value is: $((${a[$counter]}-${b[$counter]}))
counter=$(($counter+1))
done
If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.
Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/
You can change order while edit design for table.
Note that %in%
returns a logical vector of TRUE
and FALSE
. To negate it, you can use !
in front of the logical statement:
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
!where_case_travelled_1 %in%
c('Outside Canada','Outside province/territory of residence but within Canada'))
Regarding your original approach with -c(...)
, -
is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")
). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -
.
The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css
file.
Firstly, in case of using a default navigation bar (the gray one), the .navbar-default
class will be used and the text is colored as dark gray.
.navbar-default .navbar-text {
color: #777;
}
The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.
.navbar-inverse .navbar-text {
color: #999;
}
So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.
NOTE: you could also use the customizer provided by Twitter Bootstrap
, in the Navbar
section.
Here is a script which generates grant queries for a particular table. It omits owner's privileges.
SELECT
format (
'GRANT %s ON TABLE %I.%I TO %I%s;',
string_agg(tg.privilege_type, ', '),
tg.table_schema,
tg.table_name,
tg.grantee,
CASE
WHEN tg.is_grantable = 'YES'
THEN ' WITH GRANT OPTION'
ELSE ''
END
)
FROM information_schema.role_table_grants tg
JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
WHERE
tg.table_schema = 'myschema' AND
tg.table_name='mytable' AND
t.tableowner <> tg.grantee
GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;
You may have this issue as well if you have environment variable GCC_ROOT pointing to a wrong location. Probably simplest fix could be (on *nix like system):
unset GCC_ROOT
in more complicated cases you may need to repoint it to proper location
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator
. Some lists like LinkedList
will iterate faster with an Iterator
versus get(i)
. This is because because link list's iterator keeps track of the current pointer. Whereas each get
in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator
because it will be using Collection
s iterator, which in theory is optimized for the collection type.
If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.
However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:
alias = {
'a': 'id1',
'b': 'id1',
'c': 'id2',
'd': 'id2'
}
dictionary = {
'id1': 1,
'id2': 2
}
dictionary[alias['a']]
If you need to add to the dictionary you could write a function like this for using both dictionaries:
def add(key, id, value=None)
if id in dictionary:
if key in alias:
# Do nothing
pass
else:
alias[key] = id
else:
dictionary[id] = value
alias[key] = id
add('e', 'id2')
add('f', 'id3', 3)
While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.
you can set PYTHONPATH
, by os.environ['PATHPYTHON']=/some/path
, then you need to call os.system('python')
to restart the python shell to make the newly added path effective.
Another option for Windows that will automatically use the most recent version of Python installed, and also doesn't make you look for the installation path:
Target: pyw -m idlelib
Start in: Wherever you want
I have encountered this issue with play-services:5.0.89. Upgrading to 6.1.11 solved problem.
Just to elaborate on Heyvoon's (2015.06.08) response using Powershell, this simple Powershell script should give you detail on %path%
$env:Path -split ";" | % {"$(test-path $_);$_"}
generating this kind of output which you can independently verify
True;C:\WINDOWS
True;C:\WINDOWS\system32
True;C:\WINDOWS\System32\Wbem
False;C:windows\System32\windowsPowerShell\v1.0\
False;C:\Program Files (x86)\Java\jre7\bin
to reassemble for updating Path:
$x=$null;foreach ($t in ($env:Path -split ";") ) {if (test-path $t) {$x+=$t+";"}};$x
This will only return 1 row, because you're just selecting a COUNT()
. you will use mysql_num_rows()
on the $query
in this case.
If you want to get a count of each of the ID
's, add GROUP BY id
to the end of the string.
Performance-wise, don't ever ever ever use *
in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *
. This is because *
has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
I would like to expand the answer of Jason Bunting
like this
ActionResult action = new SampelController().Index(2, "text");
return action;
And Eli will be here for something idea on how to make it generic variable
Can get all types of controller