you could use setBackgroundResource()
instead i.e. relativeLayout.setBackgroundResource(R.drawable.back);
this works for me.
A temporary work around would be to set the path from the terminal itself. Worked for me after that. Running as administrator also works. Both M2 and M2_HOME are already set as system variables in my case.
My team ran into this problem when using Node with React Native and PouchDB. Here is how we solved it...
NPM install buffer:
$ npm install --save buffer
Ensure Buffer
, btoa
, and atob
are loaded as a globals:
global.Buffer = global.Buffer || require('buffer').Buffer;
if (typeof btoa === 'undefined') {
global.btoa = function (str) {
return new Buffer(str, 'binary').toString('base64');
};
}
if (typeof atob === 'undefined') {
global.atob = function (b64Encoded) {
return new Buffer(b64Encoded, 'base64').toString('binary');
};
}
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:
function showElementInPopUp(elementId) {
var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
if ($("#"+fancyboxAnchorElementId).length == 0) {
$("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
$("#"+fancyboxAnchorElementId).fancybox();
}
$("#" + fancyboxAnchorElementId).click();
}
Additional explanation: If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
I find this simple technique useful to type-check for String -
String(x) === x // true, if x is a string
// false in every other case
const test = x =>_x000D_
console.assert_x000D_
( String(x) === x_x000D_
, `not a string: ${x}`_x000D_
)_x000D_
_x000D_
test("some string")_x000D_
test(123) // assertion failed_x000D_
test(0) // assertion failed_x000D_
test(/some regex/) // assertion failed_x000D_
test([ 5, 6 ]) // assertion failed_x000D_
test({ a: 1 }) // assertion failed_x000D_
test(x => x + 1) // assertion failed
_x000D_
The same technique works for Number too -
Number(x) === x // true, if x is a number
// false in every other case
const test = x =>_x000D_
console.assert_x000D_
( Number(x) === x_x000D_
, `not a number: ${x}`_x000D_
)_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123) _x000D_
test(0) _x000D_
test(/some regex/) // assertion failed_x000D_
test([ 5, 6 ]) // assertion failed_x000D_
test({ a: 1 }) // assertion failed_x000D_
test(x => x + 1) // assertion failed
_x000D_
And for RegExp -
RegExp(x) === x // true, if x is a regexp
// false in every other case
const test = x =>_x000D_
console.assert_x000D_
( RegExp(x) === x_x000D_
, `not a regexp: ${x}`_x000D_
)_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123) // assertion failed_x000D_
test(0) // assertion failed_x000D_
test(/some regex/) _x000D_
test([ 5, 6 ]) // assertion failed_x000D_
test({ a: 1 }) // assertion failed_x000D_
test(x => x + 1) // assertion failed
_x000D_
Same for Object -
Object(x) === x // true, if x is an object
// false in every other case
NB, regexps, arrays, and functions are considered objects too.
const test = x =>_x000D_
console.assert_x000D_
( Object(x) === x_x000D_
, `not an object: ${x}`_x000D_
)_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123) // assertion failed_x000D_
test(0) // assertion failed_x000D_
test(/some regex/) _x000D_
test([ 5, 6 ]) _x000D_
test({ a: 1 }) _x000D_
test(x => x + 1)
_x000D_
But, checking for Array is a bit different -
Array.isArray(x) === x // true, if x is an array
// false in every other case
const test = x =>_x000D_
console.assert_x000D_
( Array.isArray(x)_x000D_
, `not an array: ${x}`_x000D_
)_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123) // assertion failed_x000D_
test(0) // assertion failed_x000D_
test(/some regex/) // assertion failed_x000D_
test([ 5, 6 ]) _x000D_
test({ a: 1 }) // assertion failed_x000D_
test(x => x + 1) // assertion failed
_x000D_
This technique does not work for Functions however -
Function(x) === x // always false
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Get Version using this.getClass().getPackage().getImplementationVersion()
PS Don't forget to add:
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
/* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();
If you are in Windows and want use a GUI, with puttygen you can import your private key into it:
Once imported, you can save its public key and compare it to yours.
Using ${mySet.toArray[0]} does not work.
I do not think it is possible without having forEach loop at least one iteration.
For Visual Studio users: Right click on the npm folder and "Restore Packages".
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
According to pip documentation at
http://pip.readthedocs.org/en/stable/user_guide/#configuration
You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows
On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf
On Windows, the configuration file is: %HOME%\pip\pip.ini
The %HOME% is located in C:\Users\Bob
on windows assuming your name is Bob
On linux the $HOME
directory can be located by using cd ~
You may have to create the pip.ini
file when you find your pip directory. Within your pip.ini
or pip.config
you will then need to put (assuming your on windows) something like
[global]
target=C:\Users\Bob\Desktop
Except that you would replace C:\Users\Bob\Desktop
with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path
After saving the command would then be
pip install pandas
However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.
I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query()
in the watch section, and I add xdebugSettings
node like these lines for get non truncate value in the launch.json.
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000,
"xdebugSettings": {
"max_data": -1,
"max_children": -1
}
},
And run my debuger with the breakpoint and finally just select my expresion and do click right > copy value.
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
Note that exit codes != 0 are used to report error. So, it's better to do:
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
instead of
# will fail for error codes > 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
To do it exactly your way? You could use the for...else structure
for url in list_of_urls:
for url_dict in urls:
if url_dict['url'] == url:
url_dict['nbr'] += 1
break
else:
urls.append(dict(url=url, nbr=1))
But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:
urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}
for url in list_of_urls:
if url in urls:
urls[url]['nbr'] += 1
else:
urls[url] = dict(url=url, nbr=1)
A few things to note in that second example:
urls
removes the need for going through the whole urls
list when testing for one single url
. This approach will be faster.dict( )
instead of braces makes your code shorterlist_of_urls
, urls
and url
as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit
, urls_already_visited
and current_url
. I know, it's longer. But it's clearer.And of course I'm assuming that dict(url='http://www.google.fr', nbr=1)
is a simplification of your own data structure, because otherwise, urls
could simply be:
urls = {'http://www.google.fr':1}
for url in list_of_urls:
if url in urls:
urls[url] += 1
else:
urls[url] = 1
Which can get very elegant with the defaultdict stance:
urls = collections.defaultdict(int)
for url in list_of_urls:
urls[url] += 1
Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM
from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int)
.
However a hard kill (kill -9
or kill -SIGKILL
) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.
Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
I'm pretty new to iOS development. Apparently this problem for me was a result of opening the .xcodeproj Xcode project instead of the .xcworkspace Xcode workspace. I opened the workspace instead and the error has gone away.
Return as a tuple, e.g.
def foo (a):
x=a
y=a*2
return (x,y)
If you want to SELECT
based on the value of another SELECT
, then you probably want a "subselect":
http://beginner-sql-tutorial.com/sql-subquery.htm
For example, (from the link above):
You want the first and last names from table "student_details" ...
But you only want this information for those students in "science" class:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...
IMHO...
Encapsulation: hiding data using getters and setters etc.
Abstraction: hiding implementation using abstract classes and interfaces etc.
You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.
ArrayList<? extends Object>
is an ArrayList whose type parameter is known to be Object
or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>
.
That is, you can put an ArrayList<String>
into a variable declared with ArrayList<?>
. That's why a1.add(3)
is a compile time error. a1
's declared type permits a1
to be an ArrayList<String>
, to which no Integer
can be added.
Clearly, an ArrayList<?>
is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:
It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments
ArrayList<ArrayList<?>>
in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?>
only contains but is not a wildcard type, the above rule does not apply.
I think this is the right way :
git merge --abort
git fetch --all
Then, you have two options:
git reset --hard origin/master
OR If you are on some other branch:
git reset --hard origin/<branch_name>
You can use .prop() with tagName
as the name of the property that you want to get:
$("#elementId").prop('tagName');
var popupWindow=null;
function popup()
{
popupWindow = window.open('child_page.html','name','width=200,height=200');
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
and then declare these functions in the body tag of parent window
<body onFocus="parent_disable();" onclick="parent_disable();">
As you requested here is the complete html code of the parent window
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
Content of new.jsp below
<html>
<body>
I am child
</body>
</html>
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
If you fiddle with browser versions it leads to no good very often. You don't want to implement it by yourself. But you can Modernizr made by Paul Irish and other smart folks. It will detect what the browser actually can do and put apropriate classes in <html>
element. However with Modernizr, you can test IE version like this:
$('html.lt-ie9').each() {
// this will execute if browser is IE 8 or less
}
Similary, you can use .lt-ie8
, and .lt-ie7
.
In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png
. This will work fine because browser will make request to server for that image and webpack will be able serve that image.
I fixed it by setting up env. variable JAVA_HOME.
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
You could just add a few COUNTIF
statements together:
=COUNTIF(A1:A196,"yes")+COUNTIF(A1:A196,"no")+COUNTIF(J1:J196,"agree")
This will give you the result you need.
EDIT
Sorry, misread the question. Nicholas is right that the above will double count. I wasn't thinking of the AND
condition the right way. Here's an alternative that should give you the correct results, which you were pretty close to in the first place:
=SUM(COUNTIFS(A1:A196,{"yes","no"},J1:J196,"agree"))
Since you cannot have two methods with the same name and signature you have to use the ActionName
attribute:
[HttpGet]
public ActionResult Index()
{
// your code
return View();
}
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
// your code
return View();
}
Also see "How a Method Becomes An Action"
./bilet.sh: line 6: [: 7]: integer expression expected
Be careful with " "
./bilet.sh: line 9: [: missing `]'
This is because you need to have space between brackets like:
if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]
look: added space, and no " "
(.//*[table-locator])[n]
where n
represents the specific line.
First error: You're casting a ClientThread
as a String
for some reason.
Second error: You're not calling remove
on your List
.
Is is homework? If so, you might want to use the tag.
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
This is the 2nd of two answers.
If you want to just strip all namespaces arbitrarily from a document during serialization, you can do this by implementing your own XmlWriter.
The easiest way is to derive from XmlTextWriter and override the StartElement method that emits namespaces. The StartElement method is invoked by the XmlSerializer when emitting any elements, including the root. By overriding the namespace for each element, and replacing it with the empty string, you've stripped the namespaces from the output.
public class NoNamespaceXmlWriter : XmlTextWriter
{
//Provide as many contructors as you need
public NoNamespaceXmlWriter(System.IO.TextWriter output)
: base(output) { Formatting= System.Xml.Formatting.Indented;}
public override void WriteStartDocument () { }
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement("", localName, "");
}
}
Suppose this is the type:
// explicitly specify a namespace for this type,
// to be used during XML serialization.
[XmlRoot(Namespace="urn:Abracadabra")]
public class MyTypeWithNamespaces
{
// private fields backing the properties
private int _Epoch;
private string _Label;
// explicitly define a distinct namespace for this element
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
set { _Label= value; }
get { return _Label; }
}
// this property will be implicitly serialized to XML using the
// member name for the element name, and inheriting the namespace from
// the type.
public int Epoch
{
set { _Epoch= value; }
get { return _Epoch; }
}
}
Here's how you would use such a thing during serialization:
var o2= new MyTypeWithNamespaces { ..intializers.. };
var builder = new System.Text.StringBuilder();
using ( XmlWriter writer = new NoNamespaceXmlWriter(new System.IO.StringWriter(builder)))
{
s2.Serialize(writer, o2, ns2);
}
Console.WriteLine("{0}",builder.ToString());
The XmlTextWriter is sort of broken, though. According to the reference doc, when it writes it does not check for the following:
Invalid characters in attribute and element names.
Unicode characters that do not fit the specified encoding. If the Unicode characters do not fit the specified encoding, the XmlTextWriter does not escape the Unicode characters into character entities.
Duplicate attributes.
Characters in the DOCTYPE public identifier or system identifier.
These problems with XmlTextWriter have been around since v1.1 of the .NET Framework, and they will remain, for backward compatibility. If you have no concerns about those problems, then by all means use the XmlTextWriter. But most people would like a bit more reliability.
To get that, while still suppressing namespaces during serialization, instead of deriving from XmlTextWriter, define a concrete implementation of the abstract XmlWriter and its 24 methods.
An example is here:
public class XmlWriterWrapper : XmlWriter
{
protected XmlWriter writer;
public XmlWriterWrapper(XmlWriter baseWriter)
{
this.Writer = baseWriter;
}
public override void Close()
{
this.writer.Close();
}
protected override void Dispose(bool disposing)
{
((IDisposable) this.writer).Dispose();
}
public override void Flush()
{
this.writer.Flush();
}
public override string LookupPrefix(string ns)
{
return this.writer.LookupPrefix(ns);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
this.writer.WriteBase64(buffer, index, count);
}
public override void WriteCData(string text)
{
this.writer.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
this.writer.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
this.writer.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
this.writer.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
this.writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
this.writer.WriteEndAttribute();
}
public override void WriteEndDocument()
{
this.writer.WriteEndDocument();
}
public override void WriteEndElement()
{
this.writer.WriteEndElement();
}
public override void WriteEntityRef(string name)
{
this.writer.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
this.writer.WriteFullEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
this.writer.WriteProcessingInstruction(name, text);
}
public override void WriteRaw(string data)
{
this.writer.WriteRaw(data);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
this.writer.WriteRaw(buffer, index, count);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
this.writer.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteStartDocument()
{
this.writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
this.writer.WriteStartDocument(standalone);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
this.writer.WriteStartElement(prefix, localName, ns);
}
public override void WriteString(string text)
{
this.writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
this.writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteValue(bool value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(decimal value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(double value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(int value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(long value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(object value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(float value)
{
this.writer.WriteValue(value);
}
public override void WriteValue(string value)
{
this.writer.WriteValue(value);
}
public override void WriteWhitespace(string ws)
{
this.writer.WriteWhitespace(ws);
}
public override XmlWriterSettings Settings
{
get
{
return this.writer.Settings;
}
}
protected XmlWriter Writer
{
get
{
return this.writer;
}
set
{
this.writer = value;
}
}
public override System.Xml.WriteState WriteState
{
get
{
return this.writer.WriteState;
}
}
public override string XmlLang
{
get
{
return this.writer.XmlLang;
}
}
public override System.Xml.XmlSpace XmlSpace
{
get
{
return this.writer.XmlSpace;
}
}
}
Then, provide a derived class that overrides the StartElement method, as before:
public class NamespaceSupressingXmlWriter : XmlWriterWrapper
{
//Provide as many contructors as you need
public NamespaceSupressingXmlWriter(System.IO.TextWriter output)
: base(XmlWriter.Create(output)) { }
public NamespaceSupressingXmlWriter(XmlWriter output)
: base(XmlWriter.Create(output)) { }
public override void WriteStartElement(string prefix, string localName, string ns)
{
base.WriteStartElement("", localName, "");
}
}
And then use this writer like so:
var o2= new MyTypeWithNamespaces { ..intializers.. };
var builder = new System.Text.StringBuilder();
var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };
using ( XmlWriter innerWriter = XmlWriter.Create(builder, settings))
using ( XmlWriter writer = new NamespaceSupressingXmlWriter(innerWriter))
{
s2.Serialize(writer, o2, ns2);
}
Console.WriteLine("{0}",builder.ToString());
Credit for this to Oleg Tkachenko.
The following methods actually work.
if you wish - using a theme
By default a buttons color is android:colorAccent
. So, if you create a style like this...
<style name="Button.White" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">@android:color/white</item>
</style>
You can use it like this...
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/Button.White"
/>
alternatively - using a tint
You can simply add android:backgroundTint
for API Level 21 and higher, or app:backgroundTint
for API Level 7 and higher.
For more information, see this blog.
If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.
Try:
document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";
An old post, but I love to share as I have the same case but I finally knew the problem :
Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.
Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.
But please inspect this sample that did not heed the above case :
<div class="btn-list" id="selected-country"></div>
Dynamically appended :
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function is working good by clicking the button :
$(document).ready(function() {
$('#selected-country').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
})
or you can use body like :
$('body').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
compare to this that not working :
$(document).ready(function() {
$('.btn-map').on("click", function() {
var datacountry = $(this).data('country'); alert(datacountry);
});
});
hope it will help
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
I´m frequently running into this issue on some custom properties that could not be found using IntelliJ IDEA - likely after changing branches.
What helpes in my case is
File -> Invalidate Caches / Restart
I had the assumption that it is more likely a Gradle caching issue than an IDE issue, but ./gradle clean did not help
you can try chsh -s /bin/bash
to set the bash as the default,
or chsh -s /bin/zsh
to set the zsh as the default.
Terminal will need a restart to take effect.
Readonly textbox in Asp.net
<asp:TextBox ID="t" runat="server" Style="margin-left: 20px; margin-top: 24px;"
Width="335px" Height="41px" ReadOnly="true"></asp:TextBox>
If you are Windows guy and using "Tortoise SVN' user.
Select the File. Right Click. Option 'Tortoise SVN' --> get Lock. Use option 'Steal The Lock'.
To determine which line something is on you have to search all the code for the code that occupies the particular line of interest and count the "\n" characters from the top to this of interest and add 1.
I am actually doing this very thing in an application I am writing. It is a best practices validator for HTML and is still heavily under development, but the error output process that you would be interested in is complete.
In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]
from typing import Tuple
def f() -> Tuple[dict, str]:
a = {1: 2}
b = "hello"
return a, b
You can do this very easily in Android Studio.
Create a libraries
folder underneath your project main directory. For example, if your project is OpenCVExamples
, you would create a OpenCVExamples/libraries
folder.
Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java
folder, rename it to opencv
.
Now copy the complete opencv directory from the SDK into the libraries folder you just created.
Now create a build.gradle
file in the opencv
directory with the following contents
apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.+'
}
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 19
versionCode 2480
versionName "2.4.8"
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
aidl.srcDirs = ['src']
}
}
}
Edit your settings.gradle file in your application’s main directory and add this line:
include ':libraries:opencv'
Sync your project with Gradle and it should looks like this
Right click on your project then click on the Open Module Settings
then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.
Choose Module dependency
. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.
Create a jniLibs
folder in the /app/src/main/
location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs
from the OpenCV SDK.
Click OK. Now everything done, go and enjoy with OpenCV.
In addition to the previous replies, I would like to introduce another function.
numpy.random.shuffle
as well as random.shuffle
perform in-place shuffling. However, if you want to return a shuffled array numpy.random.permutation
is the function to use.
make sure your controller extends Symfony\Bundle\FrameworkBundle\Controller\Controller;
you should also check app/console debug:router
in terminal to see what name symfony has named the route
in my case it used a minus instead of an underscore
i.e blog-show
$uri = $this->generateUrl('blog-show', ['slug' => 'my-blog-post']);
In the question, you link to the maths for when rectangles are at arbitrary angles of rotation. If I understand the bit about angles in the question however, I interpret that all rectangles are perpendicular to one another.
A general knowing the area of overlap formula is:
Using the example:
1 2 3 4 5 6 1 +---+---+ | | 2 + A +---+---+ | | B | 3 + + +---+---+ | | | | | 4 +---+---+---+---+ + | | 5 + C + | | 6 +---+---+
1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates
1 3 4 5 6
2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates
1 2 3 4 6
3) create a 2D array by number of gaps between the unique x coordinates * number of gaps between the unique y coordinates.
4 * 4
4) paint all the rectangles into this grid, incrementing the count of each cell it occurs over:
1 3 4 5 6 1 +---+ | 1 | 0 0 0 2 +---+---+---+ | 1 | 1 | 1 | 0 3 +---+---+---+---+ | 1 | 1 | 2 | 1 | 4 +---+---+---+---+ 0 0 | 1 | 1 | 6 +---+---+
5) As you paint the rectangles, its easy to intercept the overlaps.
$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$firstValue = each($array)[1];
This is much more efficient than array_values()
because the each()
function does not copy the entire array.
For more info see http://www.php.net/manual/en/function.each.php
In Eclipse Neon.3, as well as in the new Eclipse Photon (4.8.0), I can resize the font easily with Ctrl + Shift + + and -, without any plugin or special key binding.
At least in Editor Windows (this does not work in other Views like Console, Project Explorer etc).
Given a starting directory as a String
String
path as the parameter. In the method:listFiles
methodvar ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});
If the end user has Access, it might be easier to develop the whole thing in Access. Access has some WYSIWYG form design tools built-in.
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
if you are using SQL 2012 you should try
SELECT ID,
AccountID,
Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY AccountID rows between unbounded preceding and current row ) AS TopBorcT,
FROM tCariH
if available, better order by date column.
Its reaily good and working solution for push.
Please try it
I don't want to suggest a product out of turn, since getting Intellisense running is probably the best option, but I've struggled with the accursed no intellisense on Management Studio for months. Reinstallation, CU7 update, refreshing caches, sacrificing chickens to pagan gods; nothing has helped.
I was about to pay for RedGate's SqlPrompt (pretty damned pricey, $195 US), when I found SqlComplete.
http://www.devart.com/dbforge/sql/sqlcomplete/?gclid=CN2xs_Lw7akCFcYZHAodpicXXw
There is a free version which does the basics, and the full version is only $50!
I'm a database architect, and while I can remember the commands, auto complete saves me heaps of time. If you're stuck and can't get Intellisense to work, try SqlComplete. It saved me hours of hassle.
Example code (without exception-handling):
XMLGregorianCalendar xgc =
DatatypeFactory // Data-type converter.
.newInstance() // Instantiate a converter object.
.newXMLGregorianCalendar( // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
GregorianCalendar.from( // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
LocalDate // Modern class for representing a date-only, without time-of-day and without time zone.
.parse( "2014-01-07" ) // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern.
.atStartOfDay( ZoneOffset.UTC ) // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
) // Returns a `GregorianCalendar` object.
) // Returns a `XMLGregorianCalendar` object.
;
XMLGregorianCalendar
classAvoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar
, GregorianCalendar
, Calendar
, and Date
. Use only modern java.time classes.
When presented with a string such as "2014-01-07"
, parse as a LocalDate
.
LocalDate.parse( "2014-01-07" )
To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.
LocalDate.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
This returns a ZonedDateTime
object.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
;
zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]
But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC
constant as our ZoneId
argument.
ZonedDateTime zdt =
LocalDate
.parse( "2014-01-07" )
.atStartOfDay( ZoneOffset.UTC )
;
zdt.toString() = 2014-01-07T00:00Z
The Z
on the end means UTC (an offset of zero), and is pronounced “Zulu”.
If you must work with legacy classes, convert to GregorianCalendar
, a subclass of Calendar
.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;
gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]
Apparently, you really need an object of the legacy class XMLGregorianCalendar
. If the calling code cannot be updated to use java.time, convert.
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc )
;
Actually, that code requires a try-catch.
try
{
XMLGregorianCalendar xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
xgc = 2014-01-07T00:00:00.000Z
Putting that all together, with appropriate exception-handling.
// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC.
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
Objects.requireNonNull( input );
if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
XMLGregorianCalendar xgc = null;
ZonedDateTime zdt = null;
try
{
zdt =
LocalDate
.parse( input )
.atStartOfDay( ZoneOffset.UTC );
}
catch ( DateTimeParseException e )
{
throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
}
GregorianCalendar gc = GregorianCalendar.from( zdt );
try
{
xgc =
DatatypeFactory
.newInstance()
.newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
Objects.requireNonNull( xgc );
return xgc ;
}
Usage.
String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );
Dump to console.
System.out.println( "xgc = " + xgc );
xgc = 2014-01-07T00:00:00.000Z
Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.
So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.
The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.
Your input string "2014-01-07"
is in standard ISO 8601 format.
The T
in the middle separates date portion from time portion.
The Z
on the end is short for Zulu and means UTC.
Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2014-01-07" ) ;
ld.toString(): 2014-01-07
ZonedDateTime
If you want to see the first moment of that day, specify a ZoneId
time zone to get a moment on the timeline, a ZonedDateTime
. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2014-01-07T00:00:00Z
For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME
and then replace the T
in the middle with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2014-01-07 00:00:00
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Another way without JavaScript is to use <form autocomplete="off">
to prevent the browser from re-filling the form with the last values.
See also this question
Tested this only with a single <input type="text"
> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.
I use and like Rapid PHP.
Just restart Visual Studio and in Test Explorer do "Run All" ... All my tests are discovered then.
I'd like to add that there is name for those inverted if's - Guard Clause. I use it whenever I can.
I hate reading code where there is if at the beginning, two screens of code and no else. Just invert if and return. That way nobody will waste time scrolling.
Since React 0.12 the API is slightly changed. The valid code to initialize myChild would be the following:
var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.
All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.
So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.
Posting the link would be pointless, please search FusedLocation with Broadcast receiver.
Thanks
I ran across this problem when a client renamed a SQL Server. The SQL Reporting Service was configured to connect to the old server name, which they had also created an alias for that redirected to the IP of the new server name.
All of their old IIS apps were working, redirecting to the new server name via the alias. On a hunch, I checked if they were running SSRS. Attempting to connect to the SSRS site Yielded the error:
"The service is not available.Contact your system administrator to resolve the issue. System administrators: The report server can’t connect to its database. Make sure the database is running and accessible. You can also check the report server trace log for details. "
It was running on the server, but failing to connect because it was using the alias for the old server name. Re-configuring SSRS to use the new server name instead of the old/alias fixed it.
Try to run it at Framework64.
Example:
32 bit
C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase
64 bit
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe D:\DemoIconOverlaySln\Demo\bin\Debug\HandleOverlayWarning\AsmOverlayIconWarning.dll /codebase
I was looking for a simple package that would do this very same task and did not find anything so I created https://github.com/gregnb/react-to-print
You can use it like so:
<ReactToPrint
trigger={() => <a href="#">Print this out!</a>}
content={() => this.componentRef}
/>
<ComponentToPrint ref={el => (this.componentRef = el)} />
Formally, True
is a Python built-in constant of bool type.
You can use Boolean operations on bool types (at the interactive python prompt for example) and convert numbers into bool types:
>>> print not True
False
>>> print not False
True
>>> print True or False
True
>>> print True and False
False
>>> a=bool(9)
>>> print a
True
>>> b=bool(0)
>>> print b
False
>>> b=bool(0.000000000000000000000000000000000001)
>>> print b
True
And there are "gotcha's" potentially with what you see and what the Python compiler sees:
>>> n=0
>>> print bool(n)
False
>>> n='0'
>>> print bool(n)
True
>>> n=0.0
>>> print bool(n)
False
>>> n="0.0"
>>> print bool(n)
True
As a hint of how Python stores bool types internally, you can cast bool types to integers and True will come out to be 1 and False 0:
>>> print True+0
1
>>> print True+1
2
>>> print False+0
0
>>> print False+1
1
In fact, Python bool
type is a subclass of Python's int
type:
>>> type(True)
<type 'bool'>
>>> isinstance(True, int)
True
The more important part of your question is "What is while True
?" is 'what is True', and an important corollary: What is false?
First, for every language you are learning, learn what the language considers 'truthy' and 'falsey'. Python considers Truth slightly differently than Perl Truth for example. Other languages have slightly different concepts of true / false. Know what your language considers to be True and False for different operations and flow control to avoid many headaches later!
There are many algorithms where you want to process something until you find what you are looking for. Hence the infinite loop or indefinite loop. Each language tend to have its own idiom for these constructs. Here are common C infinite loops, which also work for Perl:
for(;;) { /* loop until break */ }
/* or */
while (1) {
return if (function(arg) > 3);
}
The while True:
form is common in Python for indefinite loops with some way of breaking out of the loop. Learn Python flow control to understand how you break out of while True
loops. Unlike most languages, for example, Python can have an else
clause on a loop. There is an example in the last link.
You can just change the project structure to add that folder as a "source" directory.
Project Structure ? Modules ? Click the generated-sources
folder and make it a sources
folder.
Or:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>test</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/target/generated-sources</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
use the pow
function (it takes float
s/double
s though).
man pow
:
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
EDIT: For the special case of positive integer powers of 2
, you can use bit shifting: (1 << x)
will equal 2
to the power x
. There are some potential gotchas with this, but generally, it would be correct.
Take a look here: https://github.com/davidcoallier/node-php
From their read me:
Inline PHP Server Running on Node.js
Be worried, be very worried. The name NodePHP takes its name from the fact that we are effectively turning a nice Node.js server into a FastCGI interface that interacts with PHP-FPM.
This is omega-alpha-super-beta-proof-of-concept but it already runs a few simple scripts. Mostly done for my talks on Node.js for PHP Developers this turns out to be quite an interesting project that we are most likely be going to use with Orchestra when we decide to release our Inline PHP server that allows people to run PHP without Apache, Nginx or any webserver.
Yes this goes against all ideas and concepts of Node.js but the idea is to be able to create a web-server directly from any working directory to allow developers to get going even faster than it was before. No need to create vhosts or server blocks ore modify your /etc/hosts anymore.
I simply just unistalled all my pods and reinstalled them. I also got rid of some pods i did not use.
Use -50%
instead of +50%
They will be aligned to left..
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
You can use a conditional expression:
x if x is not None else some_value
Example:
In [22]: x = None
In [23]: print x if x is not None else "foo"
foo
In [24]: x = "bar"
In [25]: print x if x is not None else "foo"
bar
Just in case this answer helps someone: as found here, you might save yourself a lot of trouble running Sysinternals Autoruns as administrator. Just go to the "Services" tab and delete your service.
It did the trick for me on a machine where I didn't have any permission to edit the registry.
@QueryMap
worked for me instead of FieldMap
If you have a bunch of GET params, another way to pass them into your url is a HashMap
.
class YourActivity extends Activity {
private static final String BASEPATH = "http://www.example.com";
private interface API {
@GET("/thing")
void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
API service = rest.create(API.class);
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "val1");
params.put("key2", "val2");
// ... as much as you need.
service.getMyThing(params, new Callback<String>() {
// ... do some stuff here.
});
}
}
The URL called will be http://www.example.com/thing/?key1=val1&key2=val2
try: window.document......
var body = window.document.getElementsByTagName("body")[0];
Error checking and handling is the programmer's friend. Check the return values of the initializing and executing cURL functions. curl_error()
and curl_errno()
will contain further information in case of failure:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
/* Process $content here */
// Close curl handle
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
* The curl_init()
manual states:
Returns a cURL handle on success, FALSE on errors.
I've observed the function to return FALSE
when you're using its $url
parameter and the domain could not be resolved. If the parameter is unused, the function might never return FALSE
. Always check it anyways, though, since the manual doesn't clearly state what "errors" actually are.
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
What about :
SELECT * FROM table del
LEFT JOIN table keep
ON del.id < keep.id
GROUP BY del.* HAVING count(*) > N;
It returns rows with more than N rows before. Could be useful ?
This doesn't show the window:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;
...
cmd.Start();
You can create temp stored procedures like:
create procedure #mytemp as
begin
select getdate() into #mytemptable;
end
in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..
Use a while loop that checks for the truthfulness of the array:
while array:
value = array.pop(0)
# do some calculation here
And it should do it without any errors or funny behaviour.
Checkout this wiki, specifically the section Restrictions on valid host names
Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.
The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.
I usually do like this:
from numpy import log as ln
Perhaps this can make you more comfortable.
Maybe adding the commands to executable file, setting +x permission and then executing?
ps aux | grep -ie amarok | awk '{print "kill -9 " $2}' > pk;chmod +x pk;./pk;rm pk
I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules DRY will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.
I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.
I prefer a simpler, more data driven approach wherever possible.
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
Using md5deep
:
md5deep -r FOLDER | awk '{print $1}' | sort | md5sum
You need to include a jar that this class exists in. You can find it here
If using Maven, you can add the following dependency declaration:
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
and for Gradle:
dependencies {
testImplementation 'com.google.code.findbugs:jsr305:3.0.2'
}
Its working for me Perfectly.
SELECT NAME FROM TABLE_NAME WHERE NAME = 'test Name' COLLATE NOCASE
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
You need to use DateTime.ParseExact
with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
For further reading you should see: Custom Date and Time Format Strings
public static byte[] my_int_to_bb_le(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_le(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static byte[] my_int_to_bb_be(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_be(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}
Observe if the view has the model required:
View
@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>
<div class="row">
<table class="table table-striped table-hover table-width-custom">
<thead>
<tr>
....
Controller
[HttpGet]
public ActionResult ListItems()
{
SiteStore site = new SiteStore();
site.GetSites();
IEnumerable<SiteViewModel> sites =
site.SitesList.Select(s => new SiteViewModel
{
Id = s.Id,
Type = s.Type
});
return PartialView("_ListItems", sites);
}
In my case I Use a partial view but runs in normal views
It turns out that my understanding of the error message was wrong. I'd say it features very poor choice of words. Googling around shown me someone else misunderstood the message exactly like I did - see PHP bug #66763.
After totally unhelpful "This is the way the RMs wanted it to be." response to that bug by Mike, Tyrael explains that setting it to "-1" doesn't make just the warning to go away. It does the right thing, i.e. it completely disables populating the culprit variable. Turns out that having it set to 0 STILL populates data under some circumstances. Talk about bad design! To cite PHP RFC:
Change always_populate_raw_post_data INI setting to accept three values instead of two.
- -1: The behavior of master; don't ever populate $GLOBALS[HTTP_RAW_POST_DATA]
- 0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST)
- 1/on/yes/true: BC behavior (always populate $GLOBALS[HTTP_RAW_POST_DATA])
So yeah, setting it to -1 not only avoids the warning, like the message said, but it also finally disables populating this variable, which is what I wanted.
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
Powershell also accept the C/C++/C* not operator
if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }
I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
For a class diagram using Oracle database, use the following steps:
File ? Data Modeler ? Import ? Data Dictionary ? select DB connection ? Next ? select database->select tabels -> Finish
I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {}
statements.
Each time the switch function is the same but the command we supply changes.
do.this <- "T1"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
Here it is inside a function:
FUN <- function(df, do.this){
switch(do.this,
T1={X <- t(df)
P <- colSums(df)%*%X
},
T2={X <- colMeans(df)
P <- outer(X, X)
},
stop("Enter something that switches me!")
)
return(P)
}
FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")
Don't use spaces...
(Incorrect)
SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
(Correct)
SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'
Try this on Rails
Time.new + 10.days
Try this on Ruby
require 'date'
DateTime.now.next_day(10).to_time
try execution the following command
vim .bashrc
:set ff=unix
:wq!
You tend to handle number of arguments with this sort of logic:
IF "%1"=="" GOTO HAVE_0
IF "%2"=="" GOTO HAVE_1
IF "%3"=="" GOTO HAVE_2
etc.
If you have more than 9 arguments then you are screwed with this approach though. There are various hacks for creating counters which you can find here, but be warned these are not for the faint hearted.
You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html
In a dict, if a key is an object, there are no duplicate problems.
For example:
class p(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
d = {p('k'): 1, p('k'): 2}
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.
As the answers mentioned, int
is just a number (called the unboxed type), whereas Integer
is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int
), you cannot store int
or other non-object types in collections (List
, Map
, etc.). In order to store them, you must first box them up in its corresponding boxed type.
Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:
Deque<Integer> queue;
void add(int n) {
queue.add(n);
}
int remove() {
return queue.remove();
}
Java 1.4 or earlier (no generics either):
Deque queue;
void add(int n) {
queue.add(Integer.valueOf(n));
}
int remove() {
return ((Integer) queue.remove()).intValue();
}
It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.
Hope this helps!
If you are willing to make use of C++11 std::async
and std::future
for running your tasks, then you can utilize the wait_for
function of std::future
to check if the thread is still running in a neat way like this:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
/* Run some task on new thread. The launch policy std::launch::async
makes sure that the task is run asynchronously on a new thread. */
auto future = std::async(std::launch::async, [] {
std::this_thread::sleep_for(3s);
return 8;
});
// Use wait_for() with zero milliseconds to check thread status.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
auto result = future.get(); // Get result.
}
If you must use std::thread
then you can use std::promise
to get a future object:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a promise and get its future.
std::promise<bool> p;
auto future = p.get_future();
// Run some task on a new thread.
std::thread t([&p] {
std::this_thread::sleep_for(3s);
p.set_value(true); // Is done atomically.
});
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
Both of these examples will output:
Thread still running
This is of course because the thread status is checked before the task is finished.
But then again, it might be simpler to just do it like others have already mentioned:
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::atomic<bool> done(false); // Use an atomic flag.
/* Run some task on a new thread.
Make sure to set the done flag to true when finished. */
std::thread t([&done] {
std::this_thread::sleep_for(3s);
done = true;
});
// Print status.
if (done) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
Edit:
There's also the std::packaged_task
for use with std::thread
for a cleaner solution than using std::promise
:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a packaged_task using some task and get its future.
std::packaged_task<void()> task([] {
std::this_thread::sleep_for(3s);
});
auto future = task.get_future();
// Run task on new thread.
std::thread t(std::move(task));
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
// ...
}
t.join(); // Join thread.
}
One more point I want to add. In spring-servlet.xml
we include component scan for Controller package.
In following example we include filter annotation for controller package.
<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In applicationcontext.xml
we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
The following creates a generic function, taking an array of any size and of any type by reference:
template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
// do stuff
}
I solved changing
readable_json['firstName']
by
readable_json[0]['firstName']
The easiest way to achieve this is with a negative margin.
const deviceWidth = RN.Dimensions.get('window').width
a: {
alignItems: 'center',
backgroundColor: 'blue',
width: deviceWidth,
},
b: {
marginTop: -16,
marginStart: 20,
},
Add the below theme in values -> style.xml
<style name="Theme_Dialog" parent="android:Theme.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
Use this theme in your onCreateDialog
method like this:
Dialog dialog = new Dialog(FlightBookActivity.this,R.style.Theme_Dialog);
Define your dialog layout including title bar in the xml file and set that xml file like this:
dialog.setContentView(R.layout.your_dialog_layout);
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
Right click your project and choose properties in the properties dialog check the Java Compiler settings, maybe you have different workspace settings.
Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr
In this case:
unique_ptr<double> uptr2 (pd);
pd
will be destroyed when uptr2
goes out of scope. This facilitates memory management by automatic deletion.
The case of unique_ptr<int> uptr (new int(3));
is not different, except that the raw pointer is not assigned to any variable here.
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.
After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(
Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.
I encountered the same exact error message. I am not quite sure if my solution will solve also your issue.
In Project Structure (app) I changed the Compile SDK Version from API 22 to API 21 and changed Build Tools Version from 22.0.0 to 21.1.2.
When I downloaded the latest API 22 Adroid 5.1, every project I create is using this API and causes me the problem. Maybe, Android Team is looking for a fix for this one.
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
if you handel this from dataBase try :
<img :src="baseUrl + 'path/path' + obj.key +'.png'">
SET UP THE REPOSITORY
For Ubuntu 14.04/16.04/16.10/17.04:
sudo add-apt-repository "deb [arch=amd64] \
https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
For Ubuntu 17.10:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"
Add Docker’s official GPG key:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
Then install
$ sudo apt-get update && sudo apt-get -y install docker-ce
@echo off
echo somethink
echo Press enter to exit
set /p input=
Sub CheckValues1()
Dim rwIndex As Integer
Dim colIndex As Integer
For rwIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rwIndex, colIndex).Value <> 0 Then _
Cells(rwIndex, colIndex).Value = 0
Next colIndex
Next rwIndex
End Sub
Found this snippet on http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.
Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.
Database is like container of data with schema, and schemas is layout of the tables there data types, relations and stuff
var array = new Array();_x000D_
_x000D_
array.push('123');_x000D_
array.push('456');_x000D_
array.push('789');_x000D_
_x000D_
var _searchedIndex = $.inArray('456',array);_x000D_
alert(_searchedIndex );_x000D_
if(_searchedIndex >= 0){_x000D_
array.splice(_searchedIndex,1);_x000D_
alert(array );_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
_x000D_
Solved! The call build job: project, parameters: params
fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List
when params = [:]
. Replacing it with params = null
solved the issue.
Here the working code below.
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1')
}
}
If Android Studio directly opening your project instead of setup window, then just close the windows of all projects. Now you will able to see the startup window. If SDK is missing then it will provide option to download SDK and other required tools.
It works for me.
I was looking for a solution to this and used the indirect one found on this page initially, but I found it quite long and clunky for what I was trying to do. After a bit of research, I found a more elegant solution (to my problem) using R1C1 notation - I think you can't mix different notation styles without using VBA though.
Depending on what you're trying to do with the self referenced cell, something like this example should get a cell to reference itself where the cell is F13:
Range("F13").FormulaR1C1 = "RC"
And you can then reference cells in relative positions to that cell such as - where your cell is F13 and you need to reference G12 from it.
Range("F13").FormulaR1C1 = "R[-1]C[1]"
You're essentially telling Excel to find F13 and then move down 1 row and up one column from that.
How this fit into my project was to apply a vlookup across a range where the lookup value was relative to each cell in the range without having to specify each lookup cell separately:
Sub Code()
Dim Range1 As Range
Set Range1 = Range("B18:B23")
Range1.Locked = False
Range1.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],DATABYCODE,2,FALSE),"""")"
Range1.Locked = True
End Sub
My lookup value is the cell to the left of each cell (column -1) in my DIM'd range and DATABYCODE is the named range I'm looking up against.
Hope that makes a little sense? Thought it was worth throwing into the mix as another way to approach the problem.
The easiest way:
python 2
import urllib2, ssl
request = urllib2.Request('https://somedomain.co/')
response = urllib2.urlopen(request, context=ssl._create_unverified_context())
python 3
from urllib.request import urlopen
import ssl
response = urlopen('https://somedomain.co', context=ssl._create_unverified_context())
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');
A simple solution without using external modules:
from datetime import datetime, timezone
dt = datetime(2008, 1, 1, 0, 0, 0, 0)
int(dt.replace(tzinfo=timezone.utc).timestamp())
There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.
Imagine block elements as picture frames hanging on a wall:
With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.
1 You can alter this behavior with the box-sizing
attribute.
Indent correctly; your for
statement should be inside the with
block:
import csv
with open('v.csv', 'w') as csvfile:
cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for w, c in p.items():
cwriter.writerow(w + c)
Outside the with
block, the file is closed.
>>> with open('/tmp/1', 'w') as f:
... print(f.closed)
...
False
>>> print(f.closed)
True
there are 600 million ticks per minute. ticksperminute
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
}
This is the code what I used for the set selected value
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];_x000D_
_x000D_
_x000D_
for (var j = 0; j < countryList.length; j++) {_x000D_
//debugger_x000D_
if (countryList[j].text == "Australia") {_x000D_
console.log(countryList[j].text); _x000D_
countryList[j].isSelected = 'selected';_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
<label>Country</label>_x000D_
<select class="custom-select col-12" id="Country" name="Country" >_x000D_
<option value="0" selected>Choose...</option>_x000D_
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}" > {{country.text}}</option>_x000D_
</select>
_x000D_
try this on an angular framework
We often see the construct df.loc[subscript] = …
to assign to one DataFrame row. Mikhail_Sam posted benchmarks containing, among others, this construct as well as the method using dict and create DataFrame in the end. He found the latter to be the fastest by far. But if we replace the df3.loc[i] = …
(with preallocated DataFrame) in his code with df3.values[i] = …
, the outcome changes significantly, in that that method performs similar to the one using dict. So we should more often take the use of df.values[subscript] = …
into consideration. However note that .values
takes a zero-based subscript, which may be different from the DataFrame.index.
I used for Android Chrome "The Screen Orientation API"
To look the current orientation call console.log(screen.orientation.type) (and maybe screen.orientation.angle).
Results: portrait-primary | portrait-secondary | landscape-primary | landscape-secondary
Below is my code, I hope it'll be helpful:
var m_isOrientation = ("orientation" in screen) && (typeof screen.orientation.lock == 'function') && (typeof screen.orientation.unlock == 'function');
...
if (!isFullscreen()) return;
screen.orientation.lock('landscape-secondary').then(
function() {
console.log('new orientation is landscape-secondary');
},
function(e) {
console.error(e);
}
);//here's Promise
...
screen.orientation.unlock();
You can set any scale you wish. It`s became actual after 6+ simulator been presented
To obtain it follow next easy steps:
defaults write ~/Library/Preferences/com.apple.iphonesimulator SimulatorWindowLastScale "0.4"
You can try any scales changing 0.4 to desired value.
To reset this custom scale, just apply any standard scale from simulator menu in way described above.
It can happen when your view property name and name inside column section of data table is not matching . Make sure that property name and column data name are matching
The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.
Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !
install these ==>> pip install -U scikit-learn scipy matplotlib if still getting the same error then , make sure that your imoprted statment should be correct. i made the mistike while writing ensemble so ,(check spelling) its should be >>> from sklearn.ensemble import RandomForestClassifier
In my case fragment methods have been called after
getActivity().onBackPressed();
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
Try rmtree()
in shutil
from the Python standard library
On Safari Mac for an HLS source, I needed to use the loadeddata event instead of the metadata event.
This does it. Note that with an odd number of elements the one in the middle won't be included.
test = [1, 23, 4, 6, 7, 8, 5]
for i in range(len(test)/2):
print (test[i], test[-1-i])
Output:
(1, 5)
(23, 8)
(4, 7)
A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.
(example: the string value of {"first_name":" I have whitespace "}
will convert to "\" I have whitespace \""
)
Before you can trim anything, you'll need to remove the extra quotes first:
// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string
// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
ns := string(data)
// Make sure we don't have a blank string of "\"\"".
if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
*s = ""
return nil
}
// Remove the added wrapping quotes.
ns, err := strconv.Unquote(ns)
if err != nil {
return err
}
// We can now trim the whitespace.
*s = ScrubString(strings.TrimSpace(ns))
return nil
}
You are confusing quantmod's 'symbol' (a term relating to a code for some financial thingamuwot) with R's 'symbol', which is a 'type' in R.
You've said:
I have a character vector of stock symbols that I pass to quantmod::getSymbols() and the function returns the symbol to the environment without the quotes
Well almost. What it does is create objects with those names in the specified environment. What I think you want to do is to get things out of an environment by name. And for that you need 'get'. Here's how, example code, working in the default environment:
getSymbols('F',src='yahoo',return.class='ts') [1] "F"
so you have a vector of characters of the things you want:
> z="F"
> z
[1] "F"
and then the magic:
> summary(get(z))
F.Open F.High F.Low F.Close
Min. : 1.310 Min. : 1.550 Min. : 1.010 Min. : 1.260
1st Qu.: 5.895 1st Qu.: 6.020 1st Qu.: 5.705 1st Qu.: 5.885
Median : 7.950 Median : 8.030 Median : 7.800 Median : 7.920
Mean : 8.358 Mean : 8.495 Mean : 8.178 Mean : 8.332
3rd Qu.:11.210 3rd Qu.:11.400 3rd Qu.:11.000 3rd Qu.:11.180
Max. :18.810 Max. :18.970 Max. :18.610 Max. :18.790
and if you don't believe me:
> identical(F,get(z))
[1] TRUE
They work at different levels.
The simplest way to view the difference, from a beginner perspective is that jQuery is essentially an abstract of JavaScript, so the way we design a page for JavaScript is pretty much how we will do it for jQuery. Start with the DOM then build a behavior layer on top of that. Not so with Angular.Js. The process really begins from the ground up, so the end result is the desired view.
With jQuery you do dom-manipulations, with Angular.Js you create whole web-applications.
jQuery was built to abstract away the various browser idiosyncracies, and work with the DOM without having to add IE6 checks and so on. Over time, it developed a nice, robust API which allowed us to do a lot of things, but at its core, it is meant for dealing with the DOM, finding elements, changing UI, and so on. Think of it as working directly with nuts and bolts.
Angular.Js was built as a layer on top of jQuery, to add MVC concepts to front end engineering. Instead of giving you APIs to work with DOM, Angular.Js gives you data-binding, templating, custom components (similar to jQuery UI, but declarative instead of triggering through JS) and a whole lot more. Think of it as working at a higher level, with components that you can hook together, instead of directly at the nuts and bolts level.
Additionally, Angular.Js gives you structures and concepts that apply to various projects, like Controllers, Services, and Directives. jQuery itself can be used in multiple (gazillion) ways to do the same thing. Thankfully, that is way less with Angular.Js, which makes it easier to get into and out of projects. It offers a sane way for multiple people to contribute to the same project, without having to relearn a system from scratch.
A short comparison can be this-
And much more
Think this helps.
More can be found-
Change the start
field in package.json from
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "
to
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "
One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.
Another alternative is to represent a 2D array as an std::vector<std::vector<int> >
. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.
Here is a working CSS/small JS solution based on the answer of Sandeep Pal:
$(document).click(function (e)
{
if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
{
$("#menu-toggle3").prop('checked', false);
}
});
Try it out by clicking the checkbox and then outside of the menu:
If your web server is running php5, I believe you must use php5_value
. This resolved the same error I received when using php_value
.
You can install this Jenkins Console log plugin to write the log in your workspace as a post build step.
You have to build the plugin yourself and install the plugin manually.
Next, you can add a post build step like that:
With an additional post build step (shell script), you will be able to grep your log.
I hope it helped :)
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
I can't see that you're adding these controls to the control hierarchy. Try:
Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );
Events won't be invoked unless the control is part of the control hierarchy.
(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.
// Import ImageIcon
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);
Now run your program.
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
Just do
onclick="SubmitFrm"
The javascript:
prefix is only required for link URLs.
Collections use generics which support either reference types or wilcards. You can however use an Integer
wrapper
List<Integer> list = new ArrayList<>();
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
I guess you are trying to do something like this:
data_list = [-5, -23, 5, 0, 23, -6, 23, 67]
new_list = []
while data_list:
minimum = data_list[0] # arbitrary number in list
for x in data_list:
if x < minimum:
minimum = x
new_list.append(minimum)
data_list.remove(minimum)
print new_list
If you want your anchor to still appear to be clickable:
$("a").removeAttr("href").css("cursor","pointer");
And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in asp.net)
$("a[href='#']").removeAttr("href").css("cursor","pointer");
I need to point out here that you're incorrectly adding middleware to the application. The app.use
calls should not be done within the app.get
request handler, but outside of it. Simply call them directly after createServer
, or take a look at the other examples in the docs.
The secret you pass to express.session
should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.
If you want to store the email address in the session, simply do something along the lines of:
req.session.email = req.param('email');
With that out of the way...
If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.
What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server
is by hijacking the request
event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.
I believe you can make this work, though, with some trickery.
You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session
:
// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));
Every session store has a get(sid, callback)
method. The sid
parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid
. (But you can give it any name by specifying a key
option in your express.session
call.)
Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest
. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.
Code on the server would then look something like the following:
var io = require('socket.io'),
express = require('express');
var app = express.createServer(),
socket = io.listen(app),
store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));
app.get('/', function(req, res) {
var old = req.session.email;
req.session.email = req.param('email');
res.header('Content-Type', 'text/plain');
res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});
socket.on('connection', function(client) {
// We declare that the first message contains the SID.
// This is where we handle the first message.
client.once('message', function(sid) {
store.get(sid, function(err, session) {
if (err || !session) {
// Do some error handling, bail.
return;
}
// Any messages following are your chat messages.
client.on('message', function(message) {
if (message.email === session.email) {
socket.broadcast(message.text);
}
});
});
});
});
app.listen(4000);
This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie
header in (think WebSockets).
If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie
header, which it can't. But for other stores, you could try calling the set(sid, data, callback)
method and see what happens.
if (data[j] =='B'){
row.cells[j].title="Basic";
}
In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
There you go, this is what I used to fix your problem:
CSS CODE
nav ul { list-style-type: none; }
HTML CODE
<nav>
<ul>
<li><a href="#">Milk</a>
<ul>
<li><a href="#">Goat</a></li>
<li><a href="#">Cow</a></li>
</ul>
</li>
<li><a href="#">Eggs</a>
<ul>
<li><a href="#">Free-range</a></li>
<li><a href="#">Other</a></li>
</ul>
</li>
<li><a href="#">Cheese</a>
<ul>
<li><a href="#">Smelly</a></li>
<li><a href="#">Extra smelly</a></li>
</ul>
</li>
</ul>
</nav>
For a short answer you should use np.save
and np.load
. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.
import numpy as np
from pathlib import Path
path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)
lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2
np.save(path/'x', x)
np.save(path/'y', y)
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
print(x is x_loaded) # False
print(x == x_loaded) # [[ True True True True True]]
Expanded answer:
In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).
However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.
Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb
. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.
So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).
So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.
I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!
import numpy as np
import pickle
from pathlib import Path
path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)
lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2
# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
pickle.dump(obj={'x':x, 'y':y}, file=db_file)
## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
db_pkl = pickle.load(db_file)
print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')
Some comments on what I learned:
np.save
as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.np.savez
uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed
.npz format.
If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)hdf5
for large files. Cool! https://stackoverflow.com/a/9619713/1601580Note this is not an exhaustive answer. But for other resources check this:
np.save
): Save Numpy Array using PickleUse Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.
The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.
The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk
file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.
I know the devil is in the detail (especially where people's personal data is concerned), and that it would be very nice to have properly capitalised names, but the above kind of hassle is why the pragmatic, time-conscious amongst us use the following:
SELECT UPPER('Put YoUR O'So oddLy casED McWeird-nAme von rightHERE here')
In my experience, people are fine seeing THEIR NAME ... even when it's half way through a sentence.
Refer to: the Russians used a pencil!
copy your Dataframe column and simply apply
df=data['x']
newdf=df.str.lower()
There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.
Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.
Copy the PEM file to your Mac and set it to be read-only by your user:
chmod 400 <private-key-filename>.pem
Then you should be able to use ssh to connect to your remote server
ssh -i <private-key-filename>.pem username@hostname
function getAge(birthday) {
var today = new Date();
var thisYear = 0;
if (today.getMonth() < birthday.getMonth()) {
thisYear = 1;
} else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
thisYear = 1;
}
var age = today.getFullYear() - birthday.getFullYear() - thisYear;
return age;
}
You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).
To do so, you would
need to include fontawesome:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th
's:
<th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
Hope that helps.
The issue is with the facebook cache and solution is to refresh the facebook cache by going to the link. https://developers.facebook.com/tools/debug/og/object/
and pressing the button "Fetch New Scrape information".
Hope it helps
It's something like this, for a dotnet 2.x core console application:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
[...]
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var serviceProvider = new ServiceCollection()
.AddLogging(options => options.AddConfiguration(configuration).AddConsole())
.AddSingleton<IConfiguration>(configuration)
.AddSingleton<SomeService>()
.BuildServiceProvider();
[...]
await serviceProvider.GetService<SomeService>().Start();
The you could inject ILoggerFactory, IConfiguration in the SomeService
.
I'd do something along these lines:
$myitems =
@([pscustomobject]@{name="Joe";age=32;info="something about him"},
[pscustomobject]@{name="Sue";age=29;info="something about her"},
[pscustomobject]@{name="Cat";age=12;info="something else"})
Note that this only works in PowerShell 3, but since you did not mention the version in your question I'm assuming this does not matter for you.
Update
It has been mentioned in comments that if you do the following:
$younger = $myitems | Where-Object { $_.age -lt 20 }
Write-Host "people younger than 20: $($younger.Length)"
You won't get 1
as you might expect. This happens when a single pscustomobject
is returned. Now this is not a problem for most of other objects in PowerShell, because they have surrogate properties for Length
and Count
. Unfortunately pscustomobject
does not. This is fixed in PowerShell 6.1.0. You can work around this by using operator @()
:
$younger = @($myitems | Where-Object { $_.age -lt 20 })
For more background see here and here.
Update 2
In PowerShell 5 one can use Classes to acheive similar functionality. For example you can define a class like this:
class Person {
[string]$name
[int]$age
[string]$info; `
`
Person(
[string]$name,
[int]$age,
[string]$info
){
$this.name = $name
$this.age = $age
$this.info = $info
}
}
Backticks here are so that you could copy and paste it to the command line, they are not required in a script. Once the class is defined you can the create an array the usual way:
$myitems =@([Person]::new("Joe",32,"something about him"),
[Person]::new("Sue",29,"something about her"),
[Person]::new("Cat",12,"something else"))
Note that this way does not have the drawback mentioned in the previous update, even in PowerShell 5.
Update 3
You can also intialize a class object with a hashtable, similar to the first example. For that you need to make sure that a default contructor defined. If you do not provide any constructors, one will be created for you, but if you provide a non-default one, default constructor won't be there and you will need to define it explicitly. Here is an example with default constructor that is auto-created:
class Person {
[string]$name
[int]$age
[string]$info;
}
With that you can:
$person = @([Person]@{name='Kevin';age=36;info="something about him"}
[Person]@{name='Sue';age=29;info="something about her"}
[Person]@{name='Cat';age=12;info="something else"})
This is a bit more verbose, but also a bit more explicit. Thanks to @js2010 for pointing this out.