Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
On a system with both Python 2 and 3 installed and with pip2
-installed Pillow failing to provide Image
, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image
:
easy_install-2.7 --user PIL
or
sudo easy_install-2.7 PIL
I still think Margus's answer is the best one. However if you want to calculate the factorials of numbers within the range 0 to 1 (ie the gamma function) as well, then you cannot use that approach because the lookup table will have to contain infinite values.
However, you can approximate the values of the factorials, and it's pretty fast, faster than recursively calling itself or looping it at least (especially when values start to get bigger).
A good approximation method is Lanczos's one
Here is an implementation in JavaScript (ported from a calculator I wrote months ago):
function factorial(op) {
// Lanczos Approximation of the Gamma Function
// As described in Numerical Recipes in C (2nd ed. Cambridge University Press, 1992)
var z = op + 1;
var p = [1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 1.208650973866179E-3, -5.395239384953E-6];
var d1 = Math.sqrt(2 * Math.PI) / z;
var d2 = p[0];
for (var i = 1; i <= 6; ++i)
d2 += p[i] / (z + i);
var d3 = Math.pow((z + 5.5), (z + 0.5));
var d4 = Math.exp(-(z + 5.5));
d = d1 * d2 * d3 * d4;
return d;
}
You can now do cool stuff like factorial(0.41)
, etc however accuracy might be a little off, after all, it is an approximation of the result.
Actually more sane sources are provided by http://suckless.org look at their sbase
repository:
git clone git://git.suckless.org/sbase
They are clearer, smarter, simpler and suckless, eg ls.c
has just 369 LOC
After that it will be easier to understand more complicated GNU code.
Straight from the horse's mouth:
If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
vars()
:>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'}
— The Python Standard Library, 16.4.4.6. The Namespace object
While that particular idiom is common, even more common is for people to use =
when they mean ==
. The convention when you really mean the =
is to use an extra layer of parentheses:
while ((list = list->next)) { // yes, it's an assignment
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.You need to float the divs in required direction eg left
or right
.
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
The general theory can be found in wikipedia's article on Kademlia. The specific protocol specification used in bittorrent is here: http://wiki.theory.org/BitTorrentDraftDHTProtocol
To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...
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.
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
Microsoft always ploughs a self-defeating (at least in IE) furrow:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.
The best way, and the right way to do it is using Uri.Authority
field
Load and use Uri like so :
Uri NewUri;
if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
Console.Writeline(NewUri.Authority);
}
Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com
Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com
Input : http://localhost/default.aspx?id=12345
Output : localhost
If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx
If you are using custom cell as header, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
headerView.addSubview(headerCell)
return headerView
}
If you want to have simple view, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView = UIView()
return headerView
}
You are most likely looking for the IIS_IUSRS account.
The answer to this requires 3 steps:
argValues
). This is straight forward as it will be available as arguments
inside the function.argNames
). This not as easy and requires parsing the function. Instead of doing the complex regex yourself and worrying about edge cases (default parameters, comments, ...), you can use a library like babylon that will parse the function into an abstract syntax tree from which you can obtain the names of parameters.The code will be like this
const babylon = require("babylon")
function doSomething(a, b, c) {
// get the values of passed argumenst
const argValues = arguments
// get the names of the arguments by parsing the function
const ast = babylon.parse(doSomething.toString())
const argNames = ast.program.body[0].params.map(node => node.name)
// join the 2 arrays, by looping over the longest of 2 arrays
const maxLen = Math.max(argNames.length, argValues.length)
const args = []
for (i = 0; i < maxLen; i++) {
args.push({name: argNames[i], value: argValues[i]})
}
console.log(args)
// implement the actual function here
}
doSomething(1, 2, 3, 4)
and the logged object will be
[
{
"name": "a",
"value": 1
},
{
"name": "c",
"value": 3
},
{
"value": 4
}
]
And here's a working example https://tonicdev.com/5763eb77a945f41300f62a79/5763eb77a945f41300f62a7a
The "IN" clause is built into linq via the .Contains() method.
For example, to get all People whose .States's are "NY" or "FL":
using (DataContext dc = new DataContext("connectionstring"))
{
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}
Anytime we create a timeout we should s clear it on componentWillUnmount, if it hasn't fired yet.
let myVar;
const Component = React.createClass({
getInitialState: function () {
return {position: 0};
},
componentDidMount: function () {
myVar = setTimeout(()=> this.setState({position: 1}), 3000)
},
componentWillUnmount: () => {
clearTimeout(myVar);
};
render: function () {
return (
<div className="component">
{this.state.position}
</div>
);
}
});
ReactDOM.render(
<Component />,
document.getElementById('main')
);
This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.
int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));
The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).
long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));
Credit: http://s-j.github.io/java-float/
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
phpmyadmin doesn't follow the MySQL connection because it defines its proper collation in phpmyadmin config file.
So if we don't want or if we can't access server parameters, we should just force it to send results in a different format (encoding) compatible with client i.e. phpmyadmin
for example if both the MySQL connection collation and the MySQL charset are utf8 but phpmyadmin is ISO, we should just add this one before any select query sent to the MYSQL via phpmyadmin :
SET SESSION CHARACTER_SET_RESULTS =latin1;
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
I’m tempted to say that both are bad practices.
The use of onclick
or javascript:
should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.
Note also that external scripts get cached by the browser.
Have a look at this answer.
Some good ways of implementing cross-browser event listeners here.
I was having same problem in my ubuntu. When I run command adb devices
it shows me ?????????? No permission
.
Then I tried with adb kill-server
and then sudo su
and adb devices
. No need to run command adb start-server
devices command will start it automatically if it is not already started.
Hope this will save once one's minutes.
Here is a simple and performant solution for a cryptographically secure random string.
package main
import (
"crypto/rand"
"unsafe"
"fmt"
)
var alphabet = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func main() {
fmt.Println(generate(16))
}
func generate(size int) string {
b := make([]byte, size)
rand.Read(b)
for i := 0; i < size; i++ {
b[i] = alphabet[b[i] / 5]
}
return *(*string)(unsafe.Pointer(&b))
}
Benchmark
Benchmark 95.2 ns/op 16 B/op 1 allocs/op
As of SQL Server 2012 you no longer have to go through the hassle of deleting the bin file (which causes other side effects). You should be able to press the delete key within the MRU list of the Server Name dropdown in the Connect to Server dialog. This is documented in this Connect item and this blog post.
Note that if you have multiple entries for a single server name (e.g. one with Windows and one with SQL Auth), you won't be able to tell which one you're deleting.
I know this is an older question but this past week I started to get a similar problem, so I leave here some notes regarding the solution that fits me.
This happened only in some Windows machines using even the last JRE to date (1.8.0_45).
The Java Web Start started to load but nothing happened and none of the previous solution attempts worked.
After some digging i've found this thread, which gives the same setup and a great explanation.
https://community.oracle.com/thread/3676876
So, in conclusion, it was a memory problem in x86 JRE and since our JNLP's max heap was defined as 1024MB, we changed to 780MB as suggested and it was fixed.
However, if you need more than 780MB, can always try launching in a x64 JRE version.
This is because the StreamReader
closes the underlying stream automatically when being disposed of. The using
statement does this automatically.
However, the StreamWriter
you're using is still trying to work on the stream (also, the using
statement for the writer is now trying to dispose of the StreamWriter
, which is then trying to close the stream).
The best way to fix this is: don't use using
and don't dispose of the StreamReader
and StreamWriter
. See this question.
using (var ms = new MemoryStream())
{
var sw = new StreamWriter(ms);
var sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
If you feel bad about sw
and sr
being garbage-collected without being disposed of in your code (as recommended), you could do something like that:
StreamWriter sw = null;
StreamReader sr = null;
try
{
using (var ms = new MemoryStream())
{
sw = new StreamWriter(ms);
sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
}
finally
{
if (sw != null) sw.Dispose();
if (sr != null) sr.Dispose();
}
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector
.class {
margin:20px;
&:hover {
color:yellow;
}
}
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)
yields
0 1 2 newcol
0 1 2 3 [0, 1, 0]
1 4 5 6 [0, 0, 1]
2 7 8 9 [1, 0, 0]
You can use JavaScript
:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline(document.passForm.input1.value);
s.writeline(document.passForm.input2.value);
s.writeline(document.passForm.input3.value);
s.Close();
}
</script>
If this does not work, an alternative is the ActiveX
object:
<script type = "text/javascript">
function WriteToFile(passForm)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine(document.passForm.input.value);
s.Close();
}
</script>
Unfortunately, the ActiveX
object, to my knowledge, is only supported in IE
.
you can run raw query like this way too.
DB::table('setting_colleges')->first();
This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):
$('#domTarget').html('<img src="" />');
var url = '/some/image/path.png';
$('#domTarget img').load(function(){}).attr('src', url).error(function() {
if ( isIE ) {
var thisImg = this;
setTimeout(function() {
if ( ! thisImg.complete ) {
$(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
}
},250);
} else {
$(this).attr('src', '/web/css/img/picture-broken-url.png');
}
});
Note: You will need to supply a valid boolean state for the isIE variable.
May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML
<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
SQL is primarily a set-orientated language - it's generally a bad idea to use a loop in it.
In this case, a similar result could be achieved using a recursive CTE:
with cte as
(select 1 i union all
select i+1 i from cte where i < 5)
select dateadd(d, i-1, '2010-01-01') from cte
Here is the simplest thing I've found
-- Midnight floor of current date
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))
The DATEDIFF returns the integer number of days before or since 1900-1-1, and the Convert Datetime obligingly brings it back to that date at midnight.
Since DateDiff returns an integer you can use add or subtract days to get the right offset.
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()) + @dayOffset)
This isn't rounding this is truncating...But I think that is what is being asked. (To round add one and truncate...and that's not rounding either, that the ceiling, but again most likely what you want. To really round add .5 (does that work?) and truncate.
It turns out you can add .5 to GetDate() and it works as expected.
-- Round Current time to midnight today or midnight tomorrow
SELECT Convert(DateTime, DATEDIFF(DAY, 0, GETDATE() + .5))
I did all my trials on SQL Server 2008, but I think these functions apply to 2005 as well.
$('selector').css('cursor', 'pointer'); // 'default' to revert
I know that may be confusing per your original question, but the "finger" cursor is actually called "pointer".
The normal arrow cursor is just "default".
Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:
PathToContainingFolder =
"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])
so that
\Users\me\Desktop\New folder\file.txt
becomes
\Users\me\Desktop\New folder
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let
is a block scoped variable (as opposed to var
’s functional scoping)=>
is an arrow function that among other things replaces function
and is prepended by its parametersnumber =>
)return
you can omit the braces and the return
keyword and simply use the expressionOnly set the width
or height
, and it will scale the other automatically. And yes you can use a percentage.
The first part can be done, but requires JavaScript, so might not work for all users.
Let's start by describing DOM elements' event handling.
First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element
interface. For the purpose of assigning event handlers, Element.addListener
and Element.on
(these are equivalent) were created. So, for example, if we have html:
<div id="test_node"></div>
and we want add click
event handler.
Let's retrieve Element
:
var el = Ext.get('test_node');
Now let's check docs for click
event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
// event name event handler
el.on( 'click' , function(e, t, eOpts){
// handling event here
});
Widgets event handling is pretty much similar to DOM nodes event handling.
First of all, widgets event handling is realized by utilizing Ext.util.Observable
mixin. In order to handle events properly your widget must containg Ext.util.Observable
as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable
as a mixin by default.
For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener
). Let's for example create Button
widget and assign click
event to it. First of all you should check event's docs for handler's arguments:
click( Ext.button.Button this, Event e, Object eOpts )
Now let's use on
:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
});
The second way is to use widget's listeners config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
listeners : {
click: function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
}
});
Notice that Button
widget is a special kind of widgets. Click event can be assigned to this widget by using handler
config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
handler : function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
});
First of all you need to register an event using addEvents method:
myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
Using the addEvents
method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.
To fire your event use fireEvent method:
myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);
arg1, arg2, arg3, /* ... */
will be passed into handler. Now we can handle your event:
myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
// event handling here
console.log(arg1, arg2, arg3, /* ... */);
});
It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent
method when you are defining new widget:
Ext.define('MyCustomButton', {
extend: 'Ext.button.Button',
// ... other configs,
initComponent: function(){
this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
// ...
this.callParent(arguments);
}
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });
To prevent bubbling you can return false
or use Ext.EventObject.preventDefault()
. In order to prevent browser's default action use Ext.EventObject.stopPropagation()
.
For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:
myButton.on('click', function(btn, e){
if (e.button !== 0)
e.preventDefault();
});
C99 quotes
This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.
Definition of declarator
The term declarator will come up a lot, so let's understand it.
From the language grammar, we find that the following underline characters are declarators:
int f(int x, int y);
^^^^^^^^^^^^^^^
int f(int x, int y) { return x + y; }
^^^^^^^^^^^^^^^
int f();
^^^
int f(x, y) int x; int y; { return x + y; }
^^^^^^^
Declarators are part of both function declarations and definitions.
There are 2 types of declarators:
Parameter type list
Declarations look like:
int f(int x, int y);
Definitions look like:
int f(int x, int y) { return x + y; }
It is called parameter type list because we must give the type of each parameter.
Identifier list
Definitions look like:
int f(x, y)
int x;
int y;
{ return x + y; }
Declarations look like:
int g();
We cannot declare a function with a non-empty identifier list:
int g(x, y);
because 6.7.5.3 "Function declarators (including prototypes)" says:
3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.
It is called identifier list because we only give the identifiers x
and y
on f(x, y)
, types come after.
This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:
1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.
and the Introduction explains what is an obsolescent feature:
Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations (for implementation features) or new programs (for language [6.11] or library features [7.26]) is discouraged
f() vs f(void) for declarations
When you write just:
void f();
it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:
direct-declarator:
[...]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-list_opt )
so only the identifier-list version can be empty because it is optional (_opt
).
direct-declarator
is the only grammar node that defines the parenthesis (...)
part of the declarator.
So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:
10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.
So:
void f(void);
is the way.
This is a magic syntax explicitly allowed, since we cannot use a void
type argument in any other way:
void f(void v);
void f(int i, void);
void f(void, int);
What can happen if I use an f() declaration?
Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):
14 The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.
So you can get away with:
void f();
void f(int x) {}
Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:
void f();
void f(float x) {}
See: Why does an empty declaration work for definitions with int arguments but not for float arguments?
f() and f(void) for definitions
f() {}
vs
f(void) {}
are similar, but not identical.
6.7.5.3 Function declarators (including prototypes) says:
14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.
which looks similar to the description of f(void)
.
But still... it seems that:
int f() { return 0; }
int main(void) { f(1); }
is conforming undefined behavior, while:
int f(void) { return 0; }
int main(void) { f(1); }
is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?
TODO understand exactly why. Has to do with being a prototype or not. Define prototype.
If you are already doing databinding:
<asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" />
Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
I always decide by this rule from C++ Core Guidelines:
Prefer T* over T& when "no argument" is a valid option
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Use a bytearray
:
>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')
or, using your code but fixing the errors:
frame = b""
frame += b'\xA2'
frame += b'\x01'
frame += b'\x02'
frame += b'\x03'
frame += b'\x04'
If you have Resharper (plugin) installed, you can access a feature that allows you to analyze used references via Solution Explorer > (right click) References > Optimize References...
http://www.jetbrains.com/resharper/webhelp/Refactorings__Remove_Unused_References.html
This feature does not correctly handle:
You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
final boolean ignoreCase = true;
int substrLength = substr.length();
int strLength = str.length();
ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();
for(int i = 0; i < strLength - substrLength + 1; i++) {
if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) {
occurrenceArr.add(i);
}
}
return occurrenceArr;
}
If you would like to ignore case you could use the following:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
If you are using the Poco library, it's a one liner and it should work on all platforms I think.
Poco::Path::current()
you can use Self-Executing Anonymous Functions. this code will work:
<a href="#" onClick="(function(){
alert('Hey i am calling');
return false;
})();return false;">click here</a>
see JSfiddle
Why not try to use the Babylonian method for finding a square root.
Here is my code for it:
double sqrt(double number)
{
double error = 0.00001; //define the precision of your result
double s = number;
while ((s - number / s) > error) //loop until precision satisfied
{
s = (s + number / s) / 2;
}
return s;
}
Good luck!
Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like
Dim copyRange2 As Range
Dim copyRange3 As Range
Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)
copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")
put these near the other codings that are the same you can easily change the Ranges as you need.
I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.
I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.
I got the above error message while trying to access a file from Internal Storage using openFileInput("/Dir/data.txt")
method with subdirectory Dir
.
You cannot access sub-directories using the above method.
Try something like:
FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt"));
you can override the style on your css by referencing the offending property of the element style. On my case these two codes are set as 15px and is causing my background image to go black. So, i override them with 0px and placed the !important so it will be priority
.content {
border-bottom-left-radius: 0px !important;
border-bottom-right-radius: 0px !important;
}
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)
'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
mod_php is a PHP interpreter.
From docs, one important catch of mod_php is,
"mod_php is not thread safe and forces you to stick with the prefork mpm (multi process, no threads), which is the slowest possible configuration"
Using GNU sed
:
sed "/cdef/aline1\nline2\nline3\nline4" input.txt
If you started with:
abcd
accd
cdef
line
web
this would produce:
abcd
accd
cdef
line1
line2
line3
line4
line
web
If you want to save the changes to the file in-place, say:
sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt
You can use "+" for returning extend, instead of extending in place.
l1=range(10)
l1+[11]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
l2=range(10,1,-1)
l1+l2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]
Similarly +=
for in place behavior, but with slight differences from append
& extend
. One of the biggest differences of +=
from append
and extend
is when it is used in function scopes, see this blog post.
You need to specify data
, index
and columns
to DataFrame
constructor, as in:
>>> pd.DataFrame(data=data[1:,1:], # values
... index=data[1:,0], # 1st column as index
... columns=data[0,1:]) # 1st row as the column names
edit: as in the @joris comment, you may need to change above to np.int_(data[1:,1:])
to have correct data type.
Just another option, which I wrote:
It's overkill if this is all the date processing that you need, but it will do what you want.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
On the "edit" page, instead of including your CSS in the normal way (with a <link>
tag), write it all to a <style>
tag. Editing the innerHTML
property of that will automatically update the page, even without a round-trip to the server.
<style type="text/css" id="styles">
p {
color: #f0f;
}
</style>
<textarea id="editor"></textarea>
<button id="preview">Preview</button>
The Javascript, using jQuery:
jQuery(function($) {
var $ed = $('#editor')
, $style = $('#styles')
, $button = $('#preview')
;
$ed.val($style.html());
$button.click(function() {
$style.html($ed.val());
return false;
});
});
And that should be it!
If you wanted to be really fancy, attach the function to the keydown on the textarea, though you could get some unwanted side-effects (the page would be changing constantly as you type)
Edit: tested and works (in Firefox 3.5, at least, though should be fine with other browsers). See demo here: http://jsbin.com/owapi
You can use NumberFormat#parse
:
try
{
NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
// Not a number.
}
Try using the -Force
parameter on Remove-Item
.
I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).
$('#dropdown').find('option').each( function() {
var $this = $(this);
if ($this.text() == 'B') {
$this.attr('selected','selected');
return false;
}
});
A two value assignment can be used for this purpose. Please check my sample program below
package main
import (
"fmt"
)
func main() {
//creating a map with 3 key-value pairs
sampleMap := map[string]int{"key1": 100, "key2": 500, "key3": 999}
//A two value assignment can be used to check existence of a key.
value, isKeyPresent := sampleMap["key2"]
//isKeyPresent will be true if key present in sampleMap
if isKeyPresent {
//key exist
fmt.Println("key present, value = ", value)
} else {
//key does not exist
fmt.Println("key does not exist")
}
}
This site uses the method isEmpty()
.
Edit: content grabbed from site, before the url will going to be invalid.
Worksheets("Sheet1").Range("A1").Sort _
key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
Set nextCell = currentCell.Offset(1, 0)
If nextCell.Value = currentCell.Value Then
currentCell.EntireRow.Delete
End If
Set currentCell = nextCell
Loop
In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.
This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.
Convert.ToInt64("1100.25")
Method signature from MSDN:
public static long ToInt64(
string value
)
Remove this line from activity if you have added
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
Then set icon
getSupportActionBar().setHomeAsUpIndicator(icon);
Use SimpleDateFormat
to convert between a date string and a real Date
object. with a Date
as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat
(click the blue code link for the Javadoc).
Here's a kickoff example:
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
WHERE NOT (someColumn LIKE '%Apples%')
I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().
protected void Page_Load(object sender, EventArgs e)
{
this.BuildControlDics();
}
private void BuildControlDics()
{
_Divs = new Dictionary<MyEnum, HtmlContainerControl>();
_Divs.Add(MyEnum.One, this.divOne);
_Divs.Add(MyEnum.Two, this.divTwo);
_Divs.Add(MyEnum.Three, this.divThree);
}
And before I get down-thumbs for not answering the OP's question...
Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET? A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.
"std" is a namespace used for STL (Standard Template Library). Please refer to https://en.wikipedia.org/wiki/Namespace#Use_in_common_languages
You can either write using namespace std;
before using any stl functions, variables or just insert std::
before them.
You need to use the alias
directive for location /static
:
server {
index index.html;
server_name test.example.com;
root /web/test.example.com/www;
location /static/ {
alias /web/test.example.com/static/;
}
}
The nginx wiki explains the difference between root and alias better than I can:
Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.
Note that root
and alias
handle trailing slashes differently.
Activity.runOnUiThread()
does not work for me. I worked around this issue by creating a regular thread this way:
public class PullTasksThread extends Thread {
public void run () {
Log.d(Prefs.TAG, "Thread run...");
}
}
and calling it from the GL update this way:
new PullTasksThread().start();
You could also use the RANK function
=RANK(C2,$C$2:$C$7,0)
It would return data like your example:
| A | B | C
1 | name | position | points
2 | person1 | 1 | 10
3 | person2 | 2 | 9
4 | person3 | 2 | 9
5 | person4 | 2 | 9
6 | person5 | 5 | 8
7 | person6 | 6 | 7
The 'Points' column needs to be sorted into descending order.
I was looking for the right method to handle those radio buttons here is an example for a solution I found here:
<tr *ngFor="let entry of entries">
<td>{{ entry.description }}</td>
<td>
<input type="radio" name="radiogroup"
[value]="entry.id"
(change)="onSelectionChange(entry)">
</td>
</tr>
Notice the onSelectionChange that passes the current element to the method.
The short answer is that not only is static
useful, it is pretty well always going to be desired.
First, note that static
and constexpr
are completely independent of each other. static
defines the object's lifetime during execution; constexpr
specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr
is no longer relevant.
Every variable declared constexpr
is implicitly const
but const
and static
are almost orthogonal (except for the interaction with static const
integers.)
The C++
object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if
principle provided it can prove that no other such object can be observed.
That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr)
array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.
On the other hand, a local static const
object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.
So you should definitely use static constexpr
in your example.
However, there is one case where you wouldn't want to use static constexpr
. Unless a constexpr
declared object is either ODR-used or declared static
, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr
arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static
, since static
is likely to force the object to exist at runtime.
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
With TortoiseGit:
right click on the file and use
Context Menu ? Restore after commit
. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.
SELECT t1.username, t1.date, value
FROM MyTable as t1
INNER JOIN (SELECT username, MAX(date)
FROM MyTable
GROUP BY username) as t2 ON t2.username = t1.username AND t2.date = t1.date
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
The following solution was implemented because recently our IDE stopped compiling and building [refresh or clean] on the standard Eclipse IDE for Java Developers version. We kept receiving the error "Your project contains error(s), please fix it before running it." We reviewed all errors, cleaned over and over, rebuilt and even created a new workspace and imported the files however nothing worked. Our product manager Johnpaul, found the error with in the compiled build path and even though it was a manual fix it would come back on the next refresh or rebuild so he recommended we back-up our work-space and do a complete re-install of the developers environment.
We made the switch as a recommendation we found from: http://knol.google.com/k/fred-grott/which-eclipse-package-for-android/166jfml0mowlh/18#report-comment-166jfml0mowlh.7wc65w
We now use the Eclipse IDE [Indigo]for Java and Report Developers Windows 64 Bit without a problem.
After the IDE broke we downloaded:
We then:
Next we:
Windows 64 Bit
We kept all of the default preferences and now everything is working perfectly again. Actually better as the rewrite also solved a few problems with our app not working on some devices. No idea as to why but we aren't complaining. Hope this helps as it is not a true install however a reinstall for Fall 2011 in a Windows 7 64 bit environment.
XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
most of the answers above saying you can't do it for class file.
Even if you want to update class file you can do that also. All you need to do is that drag and drop the class file from your workspace in the jar.
In case you want to verify your changes in class file , you can do it using a decompiler like jd-gui.
Oneliner (Smaller amount of code. DRY, as you have only one NSLog
):
NSString *string = @"hello bla bla";
NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla");
Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:
Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.
Use open(file, mode)
for files.
The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.
Use open
with readline()
or readlines()
. The former will return a line at a time, while the latter returns a list of the lines.
Use split(delimiter)
to split on the comma.
Lastly, you need to cast each item to an integer: int(foo)
. You'll probably want to surround your cast with a try block followed by except ValueError
as in the link below.
You can also use 'multiple assignment' to assign a and b at once:
>>>a, b = map(int, "2342342,2234234".split(","))
>>>print a
2342342
>>>type(a)
<type 'int'>
adb -d shell
(or adb -e shell
).
This command will help you in most of the cases, if you are too lazy to type the full ID.
From http://developer.android.com/tools/help/adb.html#commandsummary:
-d
- Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.
-e
- Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
With ES6 arrow functions it will be like this:
//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
{ brand: 'Benz', top_speed: 110 },
{ brand: 'Fiat', top_speed: 90 },
{ brand: 'Aston Martin', top_speed: 70 } ]
Array.prototype.sort()
can accept a comparator function (here I used arrow notation, but ordinary functions work the same):
let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)
// [ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Porsche', top_speed: 260 } ]
The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:
let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)
//[ { brand: 'Aston Martin', top_speed: 70 },
// { brand: 'Fiat', top_speed: 90 },
// { brand: 'Benz', top_speed: 110 },
// { brand: 'Porsche', top_speed: 260 } ]
If you don't mind mutating the orginal array cars.sort(comparatorFunction)
will do the trick.
from datetime import datetime
date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'
The following function makes a deep copy of objects, it covers copying primitive, arrays as well as object
function mergeDeep (target, source) {
if (typeof target == "object" && typeof source == "object") {
for (const key in source) {
if (source[key] === null && (target[key] === undefined || target[key] === null)) {
target[key] = null;
} else if (source[key] instanceof Array) {
if (!target[key]) target[key] = [];
//concatenate arrays
target[key] = target[key].concat(source[key]);
} else if (typeof source[key] == "object") {
if (!target[key]) target[key] = {};
this.mergeDeep(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
}
According to the Android design guidelines you must use a silhouette for builder.setSmallIcon(R.drawable.some_notification_icon);
But if you still wants to show a colorful icon as a notification icon here is the trick for lollipop and above use below code. The largeIcon will act as a primary notification icon and you also need to provide a silhouette for smallIcon as it will be shown over the bottom right of the largeIcon.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
builder.setColor(context.getResources().getColor(R.color.red));
builder.setSmallIcon(R.drawable.some_notification_icon);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
}
And pre-lollipop use only .setSmallIcon(R.mipmap.ic_launcher)
with your builder.
int a = 1;
char * c = (char*)(&a); //In C++ should be intermediate cst to void*
In Xcode 5.1
Enable Done Button
Hide Keyboard when Done is pressed
Add this method to your ViewController
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
The class you apply on the div can be used to as a reference point to style elements with that div, for example.
<div class="area1">
<table>
<tr>
<td class="item">Text Text Text</td>
<td class="item">Text Text Text</td>
</tr>
</table>
</div>
.area1 { border:1px solid black; }
.area1 td { color:red; } /* This will effect any TD within .area1 */
To be super semantic you should move the class onto the table.
<table class="area1">
<tr>
<td>Text Text Text</td>
<td>Text Text Text</td>
</tr>
</table>
This works for me:
Console.OutputEncoding = System.Text.Encoding.Default;
To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:
Open Command Prompt;
Right click on the top bar of the Command Prompt;
Click Properties;
If the font is set to Raster Fonts, change it to Lucida Console.
You can just put a pause
command in the last line of your batch file:
@echo off
echo Hey, I'm just doing some work for you.
pause
Will give you something like this as output:
Hey, I'm just doing some work for you.
Press any key to continue ...
Note: Using the @echo prevents to output the command before the output is printed.
I know this question is ancient and has an accepted answer, but I found a better solution to the problem. I am posting it here so I don't create a duplicate question, and the solution is still available to others.
Switch the order of the elements. Use the :before
pseudo-element for the content that should be underneath, and adjust margins to compensate. The margin cleanup can be messy, but the desired z-index
will be preserved.
I've tested this with IE8 and FF3.6 successfully.
This one, from kristopherjohnson is heaps better:
Less lines of code
static string PrettyXml(string xml)
{
var stringBuilder = new StringBuilder();
var element = XElement.Parse(xml);
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.NewLineOnAttributes = true;
using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
{
element.Save(xmlWriter);
}
return stringBuilder.ToString();
}
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.
You can use the rpad
and lpad
functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char
or ::text
to cast them:
SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM my_table
Similar issue on Ubuntu 18 on vsphere. The cause - Config file nginx.conf contains too many log files and sockets. Sockets are treated as files in Linux. When nginx -s reload or sudo service nginx start/restart, the Too many open files error appeared in error.log.
NGINX worker processes were launched by NGINX user. Ulimit (soft and hard) for nginx user was 65536. The ulimit and setting limits.conf did not work.
The rlimit setting in nginx.conf did not help either: worker_rlimit_nofile 65536;
The solution that worked was:
$ mkdir -p /etc/systemd/system/nginx.service.d
$ nano /etc/systemd/system/nginx.service.d/nginx.conf
[Service]
LimitNOFILE=30000
$ systemctl daemon-reload
$ systemctl restart nginx.service
I know this is old post but I struggled today with this problem also and I used template from this page: http://maven.apache.org/plugins/maven-dependency-plugin/usage.html
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>[ groupId ]</groupId>
<artifactId>[ artifactId ]</artifactId>
<version>[ version ]</version>
<type>[ packaging ]</type>
<classifier> [classifier - optional] </classifier>
<overWrite>[ true or false ]</overWrite>
<outputDirectory>[ output directory ]</outputDirectory>
<destFileName>[ filename ]</destFileName>
</artifactItem>
</artifactItems>
<!-- other configurations here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
[...]
</project>
and everything works fine under m2e
1.3.1.
When I tried to use
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
I also got m2e
error.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
I'm able to make it in a native way @ jsfiddle. Hope it will help.
Post improved answer when it work, and help others.
$(function () {
$(".example").multiselect({
checkAllText : 'Select All',
uncheckAllText : 'Deselect All',
selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
},
minWidth: 325
});
$(".example").multiselect("checkAll");
});
This is another way to specify the range of the bit-vector.
x +: N, The start position of the vector is given by x and you count up from x by N.
There is also
x -: N, in this case the start position is x and you count down from x by N.
N is a constant and x is an expression that can contain iterators.
It has a couple of benefits -
It makes the code more readable.
You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.
I want to propose another way, how to solve limitation with IN operator.
For example we have following query
select *
from Users U
WHERE U.ID in (@ids)
We want to pass several IDs to filter users. Unfortunately it is not possible to do with C# in easy way. But I have fount workaround for this by using "string_split" function. We need to rewrite a bit our query to following.
declare @ids nvarchar(max) = '1,2,3'
SELECT *
FROM Users as U
CROSS APPLY string_split(@ids, ',') as UIDS
WHERE U.ID = UIDS.value
Now we can easily pass one parameter enumeration of values separated by comma.
A large number of unwanted NUL characters, say one every other byte, indicates that the file is encoded in UTF-16 and that you should use iconv
to convert it to UTF-8.
// re initialze datepicker
$(".bootstrap-datepicker").bsdatepicker({
format: "yyyy-mm-dd",
autoclose: true,
}).on('changeDate', function (ev) {
$(this).bsdatepicker('hide');
});
//
$(".dropdown-menu").css({'z-index':'1100'});
The Git Parable explains how a typical DVCS gets created and why their creators did what they did. Also, you might want to take a look at Git for Computer Scientist; it explains what each type of object in Git does, including branches and tags.
We can separate out section of which we need to convert in PDF
For example, if table is in class "pdf-table-wrap"
After this, we need to call html2canvas function combined with jsPDF
following is sample code
var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
onrendered: function(canvas) {
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var imgData = canvas.toDataURL("image/png", 1.0);
var width = canvas.width;
var height = canvas.clientHeight;
pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));
}
});
setTimeout(function() {
//jsPDF code to save file
pdf.save('sample.pdf');
}, 0);
Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/
There are two ways. the first is to completely refresh the page using typical form submission
//your_page.php
<?php
$saveSuccess = null;
$saveMessage = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' = $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
if(($saveSuccess = saveContact($data)) {
$saveMessage = 'Your submission has been saved!';
} else {
$saveMessage = 'There was a problem saving your submission.';
}
}
?>
<!-- your other html -->
<?php if($saveSuccess !== null): ?>
<p class="flash_message"><?php echo $saveMessage ?></p>
<?php endif; ?>
<form action="your_page.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<!-- the rest of your HTML -->
The second way would be to use AJAX. to do that youll want to completely seprate the form processing into a separate file:
// process.php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array(
'fullname' => $_POST['fullname'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
);
// always return true if you save the contact data ok or false if it fails
$response['status'] = saveContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header('Content-type: application/json');
echo json_encode($response);
exit;
}
?>
And then in your html/js
<form id="add_contact" action="process.php" method="post">
<fieldset>
<legend>Add New Contact</legend>
<input type="text" name="fullname" placeholder="First name and last name" required /> <br />
<input type="email" name="email" placeholder="[email protected]" required /> <br />
<input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
<input id="add_contact_submit" type="submit" name="submit" class="button" value="Add Contact" onClick="" />
<input type="button" name="cancel" class="button" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
$(function(){
$('#add_contact_submit').click(function(e){
e.preventDefault();
$form = $(this).closest('form');
// if you need to then wrap this ajax call in conditional logic
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}
});
});
});
</script>
The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:
...
startTimer = () => {
let interval = setInterval(this.timer.bind(this), 1000);
this.setState({ interval });
};
As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).
Another option is to use another arrow function:
startTimer = () => {
let interval = setInterval(() => this.timer(), 1000);
this.setState({ interval });
};
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
get all data from table
db.student.find({})
SELECT * FROM student
get all data from table without _id
db.student.find({}, {_id:0})
SELECT name, roll FROM student
get all data from one field with _id
db.student.find({}, {roll:1})
SELECT id, roll FROM student
get all data from one field without _id
db.student.find({}, {roll:1, _id:0})
SELECT roll FROM student
find specified data using where clause
db.student.find({roll: 80})
SELECT * FROM students WHERE roll = '80'
find a data using where clause and greater than condition
db.student.find({ "roll": { $gt: 70 }}) // $gt is greater than
SELECT * FROM student WHERE roll > '70'
find a data using where clause and greater than or equal to condition
db.student.find({ "roll": { $gte: 70 }}) // $gte is greater than or equal
SELECT * FROM student WHERE roll >= '70'
find a data using where clause and less than or equal to condition
db.student.find({ "roll": { $lte: 70 }}) // $lte is less than or equal
SELECT * FROM student WHERE roll <= '70'
find a data using where clause and less than to condition
db.student.find({ "roll": { $lt: 70 }}) // $lt is less than
SELECT * FROM student WHERE roll < '70'
Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
I can suggest not to extend the default value which is 1000 and extend the application functionality by serialising the request or send the request by blocks. Otherwise, you can extend this to configuration needed.
It definitely needs to set up in the php.ini
Keyboard shortcuts to that are:
For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p
For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p
It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction
sessions, but with too many connections overall.
Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.
Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.
For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.
A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.
In PostgreSQL 9.2 and above, you can use the new state_change
timestamp column and the state
field of pg_stat_activity
to implement an idle connection reaper. Have a cron job run something like this:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'regress'
AND pid <> pg_backend_pid()
AND state = 'idle'
AND state_change < current_timestamp - INTERVAL '5' MINUTE;
In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.
On Mac (on french keyboard its) cmd + shift + F
Create /res/drawable/button.xml
with the following content :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
<solid android:color="#90EE90"/>
<corners
android:bottomRightRadius="3dp"
android:bottomLeftRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp"/>
</shape>
And then you can use the following :
<Button
android:id="@+id/button_save_prefs"
android:text="@string/save"
android:background="@drawable/button"/>
Because constructors are an implementation detail - they're not something that a user of an interface/superclass can actually invoke at all. By the time they get an instance, it's already been constructed; and vice-versa, at the time you construct an object there's by definition no variable it's currently assigned to.
Think about what it would mean to force all subclasses to have an inherited constructor. I argue it's clearer to pass the variables in directly than for the class to "magically" have a constructor with a certain number of arguments just because it's parent does.
malloc will do.
int rows = 20;
int cols = 20;
int *array;
array = malloc(rows * cols * sizeof(int));
Refer the below article for help:-
http://courses.cs.vt.edu/~cs2704/spring00/mcquain/Notes/4up/Managing2DArrays.pdf
To do this for oracle sql, the syntax would be:
,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field
for this example, I look for the second '-' and take the substring to the end
Alright, so I got it working by changing this
log4j.rootLogger=DebugAppender
to this
log4j.rootLogger=DEBUG, DebugAppender
Apparently you have to specify the logging level to the rootLogger
first? I apologize if I wasted anyone's time.
Also, I decided to answer my own question because this wasn't a classpath issue.
Use which(mydata_2$height_chad1 == 2585)
Short example
df <- data.frame(x = c(1,1,2,3,4,5,6,3),
y = c(5,4,6,7,8,3,2,4))
df
x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4
which(df$x == 3)
[1] 4 8
length(which(df$x == 3))
[1] 2
count(df, vars = "x")
x freq
1 1 2
2 2 1
3 3 2
4 4 1
5 5 1
6 6 1
df[which(df$x == 3),]
x y
4 3 7
8 3 4
As Matt Weller pointed out, you can use the length
function.
The count
function in plyr
can be used to return the count of each unique column value.
I just ran into this problem on a UICollectionView and the way that i solved it similar to the answer above but in a pure UICollectionView way.
Create a custom UICollectionViewCell that contains whatever you will be filling it with to make it dynamic. I created its own .xib for it as it seems like the easiest approach.
Add constraints in that .xib that allow for the cell to be calculated from top to bottom. The re-sizing won't work if you haven't accounted for all of the height. Say you have a view on top, then a label underneath it, and another label underneath that. You would need to connect constraints to the top of the cell to the top of that view, then the bottom of the view to the top of the first label, bottom of first label to the top of the second label, and bottom of second label to bottom of cell.
Load the .xib into the viewcontroller and register it with the collectionView on viewDidLoad
let nib = UINib(nibName: CustomCellName, bundle: nil)
self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "customCellID")`
Load a second copy of that xib into the class and store it as a property so you can use it to determine the size of what that cell should be
let sizingNibNew = NSBundle.mainBundle().loadNibNamed(CustomCellName, owner: CustomCellName.self, options: nil) as NSArray
self.sizingNibNew = (sizingNibNew.objectAtIndex(0) as? CustomViewCell)!
Implement the UICollectionViewFlowLayoutDelegate
in your view controller. The method that matters is called sizeForItemAtIndexPath
. Inside that method you will need to pull the data from the datasource that is associated with that cell from the indexPath. Then configure the sizingCell and call preferredLayoutSizeFittingSize
. The method returns a CGSize which will consist of the width minus the content insets and the height that is returned from self.sizingCell.preferredLayoutSizeFittingSize(targetSize)
.
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let data = datasourceArray?[indexPath.item] else {
return CGSizeZero
}
let sectionInset = self.collectionView?.collectionViewLayout.sectionInset
let widthToSubtract = sectionInset!.left + sectionInset!.right
let requiredWidth = collectionView.bounds.size.width
let targetSize = CGSize(width: requiredWidth, height: 0)
sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
let adequateSize = self.sizingNibNew.preferredLayoutSizeFittingSize(targetSize)
return CGSize(width: (self.collectionView?.bounds.width)! - widthToSubtract, height: adequateSize.height)
}
In the class of the custom cell itself you will need to override awakeFromNib
and tell the contentView
that its size needs to be flexible
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight]
}
In the custom cell override layoutSubviews
override func layoutSubviews() {
self.layoutIfNeeded()
}
In the class of the custom cell implement preferredLayoutSizeFittingSize
. This is where you will need to do any trickery on the items that are being laid out. If its a label you will need to tell it what its preferredMaxWidth should be.
func preferredLayoutSizeFittingSize(_ targetSize: CGSize)-> CGSize {
let originalFrame = self.frame
let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth
var frame = self.frame
frame.size = targetSize
self.frame = frame
self.setNeedsLayout()
self.layoutIfNeeded()
self.label.preferredMaxLayoutWidth = self.questionLabel.bounds.size.width
// calling this tells the cell to figure out a size for it based on the current items set
let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
let newSize = CGSize(width:targetSize.width, height:computedSize.height)
self.frame = originalFrame
self.questionLabel.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth
return newSize
}
All those steps should give you the correct sizes. If your getting 0 or other funky numbers than you haven't set up your constraints properly.
1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle
$("#button").click(function() {
$(".container").css("opacity", 0.2);
$("#loading-img").css({"display": "block"});
});
CSS:
#loading-img {
background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat; /* different for testing purposes */
display: none;
height: 100px; /* for testing purposes */
z-index: 12;
}
And a demo with animated image.
What Joomla! does is defining a Constant in a root file and checking if the same is defined in the included files.
defined('_JEXEC') or die('Restricted access');
or else
one can keep all files outside the reach of an http request by placing them outside the webroot directory as most frameworks like CodeIgniter recommend.
or even by placing an .htaccess file within the include folder and writing rules, you can prevent direct access.
If you want to use a specific transform function, then all you need to do is include that function in the value. For example:
$('.user-text').css('transform', 'scale(' + ui.value + ')');
Secondly, browser support is getting better, but you'll probably still need to use vendor prefixes like so:
$('.user-text').css({
'-webkit-transform' : 'scale(' + ui.value + ')',
'-moz-transform' : 'scale(' + ui.value + ')',
'-ms-transform' : 'scale(' + ui.value + ')',
'-o-transform' : 'scale(' + ui.value + ')',
'transform' : 'scale(' + ui.value + ')'
});
jsFiddle with example: http://jsfiddle.net/jehka/230/
Try this
git clone ssh://[email protected]:11111/home/git/repo.git
Try one of this solution
In your terminal type find / -name "php.ini"
In your terminal type php -i | grep php.ini
. It should show the
file path as Configuration File (php.ini) Path => /etc
<?php
in a new line phpinfo();
This
will tell you the php.ini locationphp -a
in
the terminal and type phpinfo(); after php initiated.There are two variants of CASE
, and you're not using the one that you think you are.
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
Each condition is loosely equivalent to a if (case_value == when_value)
(pseudo-code).
However, you've put an entire condition as when_value
, leading to something like:
if (case_value == (case_value > 100))
Now, (case_value > 100)
evaluates to FALSE
, and is the only one of your conditions to do so. So, now you have:
if (case_value == FALSE)
FALSE
converts to 0
and, through the resulting full expression if (case_value == 0)
you can now see why the third condition fires.
Drop the first course_enrollment_settings
so that there's no case_value
, causing MySQL to know that you intend to use the second variant of CASE
:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
Now you can provide your full conditionals as search_condition
.
Also, please read the documentation for features that you use.
openpyxl
# -*- coding: utf-8 -*-
import openpyxl
file = 'sample.xlsx'
wb = openpyxl.load_workbook(filename=file)
# Seleciono la Hoja
ws = wb.get_sheet_by_name('Hoja1')
# Valores a Insertar
ws['A3'] = 42
ws['A4'] = 142
# Escribirmos en el Fichero
wb.save(file)
If it has happened after upgrading Android Studio, It can be caused by an out of date buildtool, Update Android SDK BuildTools
.val()
is for input elements, use .html()
instead
You shouldn't edit it, you should completely scrap it.
Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout
correctly.
Run cmd as administrator. Type iisreset
. That's it.
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:
CRLF
and LF
in the same file.How this happens is not the issue here, but it does happen.
I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:
| Resulting conversion when | Resulting conversion when | committing files with various | checking out FROM repo - | EOLs INTO repo and | with mixed files in it and | core.autocrlf value: | core.autocrlf value: -------------------------------------------------------------------------------- File | true | input | false | true | input | false -------------------------------------------------------------------------------- Windows-CRLF | CRLF -> LF | CRLF -> LF | as-is | as-is | as-is | as-is Unix -LF | as-is | as-is | as-is | LF -> CRLF | as-is | as-is Mac -CR | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF+CR | as-is | as-is | as-is | as-is | as-is | as-is
As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.
Upon checkout (3 right columns), there is only 1 case where conversion happens when:
core.autocrlf
is true
and LF
EOL.Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF
+LF
get normalized.
Note also that "old" Mac EOLs of CR
only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLF
s+LF
s, by just converting LF
s to CRLF
s, then it will leave the file in a mixed mode with "lonely" CR
s wherever a CRLF
was converted to CRCRLF
.
Git will then not convert anything, even in true
mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.
I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input
or false
mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true
.
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
Test if a file exists:
HOST="example.com"
FILE="/path/to/file"
if ssh $HOST "test -e $FILE"; then
echo "File exists."
else
echo "File does not exist."
fi
And the opposite, test if a file does not exist:
HOST="example.com"
FILE="/path/to/file"
if ! ssh $HOST "test -e $FILE"; then
echo "File does not exist."
else
echo "File exists."
fi
This should do the trick:
$('#some_select_box').click(function() {
$('option:selected', this ).remove();
});
There are two options here.
Edit
@Html.Hidden("clubid", ViewBag.Club.id)
or
@using(Html.BeginForm("action", "controller",
new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
You can proxyfy references to your object with, for example, dictionary singleton. You may store not object, but its ID or hash and access it trought the dictionary. Then when you need to remove the object you set value for its key to null.
The answer by @T.J.Crowder is Java 6 - in java 7 the valid answer is the one by @McIntosh - though its use of Charset for name for UTF -8 is discouraged:
List<String> lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
StandardCharsets.UTF_8);
for(String line: lines){ /* DO */ }
Reminds a lot of the Guava way posted by Skeet above - and of course same caveats apply. That is, for big files (Java 7):
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {}
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.
find /home/baumerf/public_html/ -mmin -60 -not -name error_log
If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:
find /home/baumerf/public_html/ -mmin -60 -not -name \*.log
Create a list of namedtuples
It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:
d = {'John':5, 'Alex':10, 'Richard': 7}
You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:
>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
How to do this:
list in random order or keeping order of collections.OrderedDict:
import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
in order, sorted by value ('score'):
import collections
Player = collections.namedtuple('Player', 'score name')
sorted with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorted with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
I know this question is old. But anyone looking to do it today here you go.
div.floatablediv{_x000D_
-webkit-column-break-inside: avoid;_x000D_
-moz-column-break-inside: avoid;_x000D_
column-break-inside: avoid;_x000D_
}_x000D_
div.floatcontainer{_x000D_
-webkit-column-count: 2;_x000D_
-webkit-column-gap: 1px;_x000D_
-webkit-column-fill: auto;_x000D_
-moz-column-count: 2;_x000D_
-moz-column-gap: 1px;_x000D_
-moz-column-fill: auto;_x000D_
column-count: 2;_x000D_
column-gap: 1px;_x000D_
column-fill: auto;_x000D_
}
_x000D_
<div style="background-color: #ccc; width: 100px;" class="floatcontainer">_x000D_
<div style="height: 50px; width: 50px; background-color: #ff0000;" class="floatablediv">_x000D_
</div>_x000D_
<div style="height: 70px; width: 50px; background-color: #00ff00;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="height: 30px; width: 50px; background-color: #0000ff;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="height: 40px; width: 50px; background-color: #ffff00;" class="floatablediv"> _x000D_
</div>_x000D_
<div style="clear:both;"></div>_x000D_
</div>
_x000D_
Another way is to get the row index and then use df.loc or df.at.
# get row index 'label' from row number 'irow'
label = df.index.values[irow]
df.at[label, 'COL_NAME'] = x
Indeed, Python does garbage collection through reference counting. As soon as the last reference to an object falls out of scope, it is deleted. In your example:
a = A()
a.kill()
I don't believe there's any way for variable 'a' to implicitly set itself to None.
HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP'])
returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.
The text before each parameter is part of the method name. From your example, the name of the method is actually
-getBusStops:forTime:
Each : represents an argument. In a method call, the method name is split at the :s and arguments appear after the :s. e.g.
[getBusStops: arg1 forTime: arg2]
A more compact and readable solution using query() is like this:
import pandas as pd
df = pandas.DataFrame(np.random.randn(5,3),columns=['A','B','C'])
print(df)
# find row with maximum A
df.query('A == A.max()')
It also returns a DataFrame instead of Series, which would be handy for some use cases.
Use the instanceof
syntax.
Like so:
Object foo = "";
if( foo instanceof String ) {
// do something String related to foo
}
In my case, I'd added a framework that must be using Objective C++. I found this post:
that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be compiled, too.
That fixed it for me.
For using "overflow: scroll" you must set "display:block" on thead and tbody. And that messes up column widths between them. But then you can clone the thead row with Javascript and paste it in the tbody as a hidden row to keep the exact col widths.
$('.myTable thead > tr').clone().appendTo('.myTable tbody').addClass('hidden-to-set-col-widths');
http://jsfiddle.net/Julesezaar/mup0c5hk/
<table class="myTable">
<thead>
<tr>
<td>Problem</td>
<td>Solution</td>
<td>blah</td>
<td>derp</td>
</tr>
</thead>
<tbody></tbody>
</table>
<p>
Some text to here
</p>
The css:
table {
background-color: #aaa;
width: 100%;
}
thead,
tbody {
display: block; // Necessary to use overflow: scroll
}
tbody {
background-color: #ddd;
height: 150px;
overflow-y: scroll;
}
tbody tr.hidden-to-set-col-widths,
tbody tr.hidden-to-set-col-widths td {
visibility: hidden;
height: 0;
line-height: 0;
padding-top: 0;
padding-bottom: 0;
}
td {
padding: 3px 10px;
}
I think should be enough to map a boolean
In code this is:
boolean isEmpty = anyCollection.stream()
.filter(p -> someFilter(p)) // Add my filter
.map(p -> Boolean.TRUE) // For each element after filter, map to a TRUE
.findAny() // Get any TRUE
.orElse(Boolean.FALSE); // If there is no match return false
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
Note: this doen't sanitize arrays:
import { isPlainObject } from 'lodash';
export const sanitize = (obj: {}) => {
if (isPlainObject(obj)) {
const sanitizedObj = {};
for (const key in obj) {
if (obj[key]) {
sanitizedObj[key] = sanitize(obj[key]);
}
}
return sanitizedObj;
} else {
return obj;
}
};
Test:
describe('sanitize', () => {
it('should keep an object if there are no empty fields', () => {
expect(sanitize({})).toEqual({});
expect(sanitize({ foo: 'bar' })).toEqual({ foo: 'bar' });
expect(sanitize({ content: { foo: 'bar' } })).toEqual({
content: { foo: 'bar' },
});
});
it('should remove empty fields from top level', () => {
expect(sanitize({ foo: '', bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: null, bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: undefined, bar: 'baz' })).toEqual({ bar: 'baz' });
});
it('should remove nested empty fields', () => {
expect(sanitize({ content: { foo: '', bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: null, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: undefined, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
});
});
For put method we have:
const putMethod = {
method: 'PUT', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
body: JSON.stringify(someData) // We send data in JSON format
}
// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
Example for someData, we can have some input fields or whatever you need:
const someData = {
title: document.querySelector(TitleInput).value,
body: document.querySelector(BodyInput).value
}
And in our data base
will have this in json
format:
{
"posts": [
"id": 1,
"title": "Some Title", // what we typed in the title input field
"body": "Some Body", // what we typed in the body input field
]
}
For delete method we have:
const deleteMethod = {
method: 'DELETE', // Method itself
headers: {
'Content-type': 'application/json; charset=UTF-8' // Indicates the content
},
// No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error
In the url we need to type the id of the of deletion: https://www.someapi/id
I've separated this answer into two(2) methods. The first method will separate your fullname field into first, middle, and last names. The middle name will show as NULL if there is no middle name.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
If( length(fullname) - length(replace(fullname, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) ,NULL)
as middle_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 3), ' ', -1) AS last_name
FROM registeredusers
This second method considers the middle name as part of the lastname. We will only select a firstname and lastname column from your fullname field.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
TRIM( SUBSTR(fullname, LOCATE(' ', fullname)) ) AS last_name
FROM registeredusers
There's a bunch of cool things you can do with substr, locate, substring_index, etc. Check the manual for some real confusion. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o
FROM Orders o
INNER JOIN Customers c
ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.
In SQL without SELECT
you cannot result anything. Instead of IF-ELSE
block I prefer to use CASE
statement for this
SELECT CASE
WHEN EXISTS (SELECT 1
FROM tblGLUserAccess
WHERE GLUserName = 'xxxxxxxx') THEN 1
ELSE 2
END
Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:
var fileName = location.href.split("/").slice(-1);
or...
var fileName = location.pathname.split("/").slice(-1)
This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.
JS:
$('.menu a').each(function() {
if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});
CSS:
a.current_page { font-size: 2em; color: red; }
I Found an easy way to do this,I've tested it,it works Properly. First I created a Windows Project,on the form I Inserted a TextBox and I named it textBox1 then I inserted a button named button1,then add a class named class1. in the class1 I created a TextBox:
class class1
{
public static TextBox txt1=new TextBox(); //a global textbox to interfece with form1
public static void Hello()
{
txt1.Text="Hello";
}
}
Now in your Form Do this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
class1.txt1=textBox1;
class1.Hello();
}
}
in the button1_Click I coppied the object textBox1 into txt1,so now txt1 has the properties of textBox1 and u can change textBox1 text in another form or class.
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql
select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...
There is some difference when we define the properties in the application.properties and application yaml.
In application.yml :
spring:
http:
multipart:
max-file-size: 256KB
max-request-size: 256KB
And in application.propeties :
spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB
Note : Spring version 4.3 and Spring boot 1.4
function in_array(needle, haystack){
var found = 0;
for (var i=0, len=haystack.length;i<len;i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
if(in_array("118",array)!= -1){
//is in array
}
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
According to the line debug1: Authentications that can continue: publickey,gssapi-with-mic
, ssh password authentication is disabled and apparently you are not using public key authentication.
Login to your server using console and open /etc/ssh/sshd_config
file with an editor with root user and look for line PasswordAuthentication
then set it's value to yes and finally restart sshd service.
I would simply add a new column to the data frame with the name I want and get the data for it from the existing column. like this:
dataf$value=dataf$Article1Order
then I remove the old column! like this:
dataf$Article1Order<-NULL
This code might seem silly! But it works perfectly...
I believe telnet 74.255.12.25 8089
. Why don't u try both
I encountered the same error, with the below code.
return this.state.employees.map((employee) => {
<option value={employee.id}>
{employee.name}
</option>
});
Above issue got resolved, when I changed curly braces to parenthesis, as indicated in the below modified code snippet.
return this.state.employees.map((employee) => (
<option value={employee.id}>
{employee.name}
</option>
));
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
have you tried to remove the timezone awareness?
from http://pytz.sourceforge.net/
naive = dt.replace(tzinfo=None)
may have to add time zone conversion as well.
edit: Please be aware the age of this answer. An answer involving ADDing the timezone info instead of removing it in python 3 is below. https://stackoverflow.com/a/25662061/93380
I just want one result
implies that you expect only one row to be returned. So either adapt your query, e.g.
SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
LIMIT 0, 1
(and then use getSingleResult()
as recommended by AdrienBrault) or fetch rows as an array and access the first item:
// ...
$players = $query->getArrayResult();
$myPlayer = $players[0];
This is what helped me:
Create a new branch with the existing one. Let's call the existing one branch_old
and new as branch_new
.
Reset branch_new
to a stable state, when you did not have any problem commit at all.
For example, to put it at your local master's level do the following:
git reset —hard master git push —force origin
cherry-pick
the commits from branch_old
into branch_new
git push
This is how Oauth 2.0 works, well explained in this article
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
For Font Awesome 5 SVG version, use
filter: drop-shadow(0 0 3px rgba(0,0,0,0.7));