While waiting for read()
or write()
to/from a file descriptor return, the process will be put in a special kind of sleep, known as "D" or "Disk Sleep". This is special, because the process can not be killed or interrupted while in such a state. A process waiting for a return from ioctl() would also be put to sleep in this manner.
An exception to this is when a file (such as a terminal or other character device) is opened in O_NONBLOCK
mode, passed when its assumed that a device (such as a modem) will need time to initialize. However, you indicated block devices in your question. Also, I have never tried an ioctl()
that is likely to block on a fd opened in non blocking mode (at least not knowingly).
How another process is chosen depends entirely on the scheduler you are using, as well as what other processes might have done to modify their weights within that scheduler.
Some user space programs under certain circumstances have been known to remain in this state forever, until rebooted. These are typically grouped in with other "zombies", but the term would not be correct as they are not technically defunct.
Yes, you need to use PropTypes.arrayOf
instead of PropTypes.array
in the code, you can do something like this:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
annotationRanges: PropTypes.arrayOf(
PropTypes.shape({
start: PropTypes.string.isRequired,
end: PropTypes.number.isRequired
}).isRequired
).isRequired
}
Also for more details about proptypes, visit Typechecking With PropTypes here
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
script.aculo.us has a slider control that might be worth checking out.
Some websites with m3u streaming cannot be downloaded in a single youtube-dl
step, you can try something like this :
$ URL=https://www.arte.tv/fr/videos/078132-001-A/cosmos-une-odyssee-a-travers-l-univers/
$ youtube-dl -F $URL | grep m3u
HLS_XQ_2 m3u8 1280x720 VA-STA, Allemand 2200k
HLS_XQ_1 m3u8 1280x720 VF-STF, Français 2200k
$ CHOSEN_FORMAT=HLS_XQ_1
$ youtube-dl -F "$(youtube-dl -gf $CHOSEN_FORMAT)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[info] Available formats for master:
format code extension resolution note
61 mp4 audio only 61k , mp4a.40.2
419 mp4 384x216 419k , avc1.66.30, mp4a.40.2
923 mp4 640x360 923k , avc1.77.30, mp4a.40.2
1737 mp4 720x406 1737k , avc1.77.30, mp4a.40.2
2521 mp4 1280x720 2521k , avc1.77.30, mp4a.40.2 (best)
$ youtube-dl --hls-prefer-native -f 1737 "$(youtube-dl -gf $CHOSEN_FORMAT $URL)" -o "$(youtube-dl -f $CHOSEN_FORMAT --get-filename $URL)"
[generic] master: Requesting header
[generic] master: Downloading webpage
[generic] master: Downloading m3u8 information
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 257
[download] Destination: Cosmos_une_odyssee_a_travers_l_univers__HLS_XQ_1__078132-001-A.mp4
[download] 0.9% of ~731.27MiB at 624.95KiB/s ETA 13:13
....
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.
client.h
#ifndef CLIENT_H
#define CLIENT_H
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);
#endif /** CLIENT_H */
Then you'd implement the .h in a .c file like so:
client.c
#include "client.h"
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
short ret = -1;
//some implementation here
return ret;
}
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.
>powershell.exe "echo la`"" >> test
>type test
la"
Below are outputs I got for other characters to escape a double quote:
la\
la^
la
la~
Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.
Just adding some extra sorting if needed
=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)
Let's add one more similar solution to the stack. This one also parses enums, and it looks nice. Very safe.
/// <summary>
/// <para>More convenient than using T.TryParse(string, out T).
/// Works with primitive types, structs, and enums.
/// Tries to parse the string to an instance of the type specified.
/// If the input cannot be parsed, null will be returned.
/// </para>
/// <para>
/// If the value of the caller is null, null will be returned.
/// So if you have "string s = null;" and then you try "s.ToNullable...",
/// null will be returned. No null exception will be thrown.
/// </para>
/// <author>Contributed by Taylor Love (Pangamma)</author>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p_self"></param>
/// <returns></returns>
public static T? ToNullable<T>(this string p_self) where T : struct
{
if (!string.IsNullOrEmpty(p_self))
{
var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
}
return null;
}
Using the android.support.v7.widget.AppCompatButton in the XML layout will allow you to avoid having to have a layout-21 or programmatically changing anything. Naturally this will also work with AppCompat v7 library.
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnOpenMainDemo"
android:textAllCaps="false"
style="@style/HGButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_main_demo"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
Hope this helps.
You don't need to use an indexer (since it a bit less typesafe). You have two options :
interface EnumServiceItem {
id: number; label: string; key: any
}
interface EnumServiceItems extends Array<EnumServiceItem>{}
// Option A
var result: EnumServiceItem[] = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
// Option B
var result: EnumServiceItems = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
]
Personally I recommend Option A (simpler migration when you are using classes not interfaces).
Another options with purrr
package:
library(dplyr)
df <- data.frame(a = NA,
b = seq(1:5),
c = c(rep(1, 4), NA))
df %>% purrr::discard(~all(is.na(.)))
df %>% purrr::keep(~!all(is.na(.)))
GCC compiles a C/C++ program into executable in 4 steps.
For example, gcc -o hello hello.c
is carried out as follows:
Preprocessing via the GNU C Preprocessor (cpp.exe
), which includes
the headers (#include
) and expands the macros (#define
).
cpp hello.c > hello.i
The resultant intermediate file "hello.i" contains the expanded source code.
The compiler compiles the pre-processed source code into assembly code for a specific processor.
gcc -S hello.i
The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".
The assembler (as.exe
) converts the assembly code into machine code in the object file "hello.o".
as -o hello.o hello.s
Finally, the linker (ld.exe
) links the object code with the library code to produce an executable file "hello".
ld -o hello hello.o ...libraries...
I had the same issue when attaching a database. It wasn't a SQL issue it was an account issue. Go to the panel control/User Account Control Settings/Set to "never notify". Finally,restart the computer and it worked for me.
If you want just a jQuery option, this will work:
$(el).stop().animate(
{rotation: 360},
{
duration: 500,
step: function(now, fx) {
$(this).css({"transform": "rotate("+now+"deg)"});
}
}
);
This works with jQuery 1.8, which takes care of CSS prefixing automatically. jQuery doesn't animate rotation so I'm putting the transform:rotate()
in the custom step
function. It might only work starting from 0.
Demo: http://jsfiddle.net/forresto/ShUgD/
IE9 and Mobile Safari 4 support CSS transforms but not CSS transitions, so I came up with this simple shim, using Modernizr feature testing:
if (Modernizr.csstransitions) {
$(el).css({
"transition": "all 500ms ease-in-out"
});
}
$(el).click(function(){
var rotateTo = 360;
if (Modernizr.csstransitions) {
$(el).css({"transform": "rotate("+rotateTo+"deg)"});
} else {
$(el).stop().animate(
{rotation: rotateTo},
{
duration: 500,
step: function(now, fx) {
$(this).css({"transform": "rotate("+now+"deg)"});
}
}
);
}
});
The above will use CSS transitions when available.
<?php echo date("H:i", time()); ?>
<?php echo $days[date("l", time())] . date(", d.m.Y", time()); ?>
Simple, this should do the trick
Here's what I did:
After building Macvim I copied mvim to one of my $PATH destinations (In this case I chose /usr/local/bin)
cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin
Then when you invoke mvim it is now recognised but there is an annoying thing. It opens the visual MacVim window, not the one in terminal. To do that, you have to invoke
mvim -v
To make sure every time you call mvim you don't have to remember to add the '-v' you can create an alias:
alias mvim='mvim -v'
However, this alias will only persist for this session of the Terminal. To have this alias executed every time you open a Terminal window, you have to include it in your .profile The .profile should be in your home directory. If it's not, create it.
cd ~
mvim -v .profile
include the alias command in there and save it.
That's it.
On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps
you have to tell angular
that you updated the content after ngAfterContentChecked
you can import ChangeDetectorRef
from @angular/core
and call detectChanges
import {ChangeDetectorRef } from '@angular/core';
constructor( private cdref: ChangeDetectorRef ) {}
ngAfterContentChecked() {
this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
this.cdref.detectChanges();
}
This could also happen if you are using CMake. If you have created a new class and you want to instantiate it, at the constructor call you will receive this error -even when the header and the cpp
files are correct- if you have not modified CMakeLists.txt
accordingly.
With CMake, every time you create a new class, before using it the header, the cpp
files and any other compilable files (like Qt ui
files) must be added to CMakeLists.txt
and then re-run cmake .
where CMakeLists.txt
is stored.
For example, in this CMakeLists.txt
file:
cmake_minimum_required(VERSION 2.8.11)
project(yourProject)
file(GLOB ImageFeatureDetector_SRC *.h *.cpp)
### Add your new files here ###
add_executable(yourProject YourNewClass.h YourNewClass.cpp otherNewFile.ui})
target_link_libraries(imagefeaturedetector ${SomeLibs})
If you are using the command file(GLOB yourProject_SRC *.h *.cpp)
then you just need to re-run cmake .
without modifying CMakeLists.txt
.
I had this problem suddenly crop up in Windows 7 with my Nexus One - somehow the USB drivers had been uninstalled. I ran android-sdk/SDK Manager.exe, checked Extras/Google USB Driver and installed it. Then I unplugged the phone and plugged it back in, and ran "adb devices" to confirm the phone was attached.
This doesn't work for all phones, just the ones listed here: http://developer.android.com/sdk/win-usb.html
This doesn't directly answer your question, but it does solve your problem...
What make of router do you have? Your router firmware may allow you to set DNS records for your local network. This is what I do with the Tomato firmware
What I did to get this to work is the following:
In the controller I added the following code:
namespace MyNameSpace.Controllers {
public class DefaultController : Controller {
// GET: Default
public ActionResult Index() {
return RedirectToAction("Index", "ControllerName", new {area = "FolderName"});
}
} }
In my RouterConfig.cs I added the following:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Default", action = "Index", id = UrlParameter.Optional});
The trick behind all this is that I made a default constructor which will always be the startup controller every time my app starts. When it hits that default controller it will redirect to any controller I specify in the default Index Action. Which in my case is
www.myurl.com/FolderName/ControllerName
.
Tuples cannot efficiently be appended like a list.
So a tuple comprehension would need to use a list internally and then convert to a tuple.
That would be the same as what you do now : tuple( [ comprehension ] )
Pro tip. If you want to turn on focus from the dev console then just open the console as a separate window from the options tab. The latest Firefox and Chrome supports this feature.
if You want to change opacity for all dialog then change in jquery-ui.css
/* Overlays */
.ui-widget-overlay
{
background: #5c5c5c url(images/ui-bg_flat_50_5c5c5c_40x100.png) 50% 50% repeat-x;
opacity: .50;
filter: Alpha(Opacity=80);
}
I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);
From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
If you use it more than once or in a loop, you could define a constant
public static final Foo[] FOO = new Foo[]{};
and do the conversion it like
Foo[] foos = fooCollection.toArray(FOO);
The toArray
method will take the empty array to determine the correct type of the target array and create a new array for you.
Here's my proposal for the update:
Collection<Foo> foos = new ArrayList<Foo>();
Collection<Bar> temp = new ArrayList<Bar>();
for (Foo foo:foos)
temp.add(new Bar(foo));
Bar[] bars = temp.toArray(new Bar[]{});
char *
and const unsigned char *
are considered unrelated types. So you want to use reinterpret_cast
.
But if you were going from const unsigned char*
to a non const
type you'd need to use const_cast
first. reinterpret_cast
cannot cast away a const
or volatile
qualification.
<?php
function strip_only($str, $tags, $stripContent = false) {
$content = '';
if(!is_array($tags)) {
$tags = (strpos($str, '>') !== false
? explode('>', str_replace('<', '', $tags))
: array($tags));
if(end($tags) == '') array_pop($tags);
}
foreach($tags as $tag) {
if ($stripContent)
$content = '(.+</'.$tag.'[^>]*>|)';
$str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
}
return $str;
}
$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...
int i = 5; char a = ((char*)&i)[0]; char b = ((char*)&i)[1];
Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!
But you probably meant "i want to stringify a number", so ignore this response :-)
In the same spirit as https://stackoverflow.com/a/6943976/7154924:
cat -A
-A, --show-all
equivalent to -vET
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
-E, --show-ends
display $ at end of each line
-T, --show-tabs
display TAB characters as ^I
Alternatively, or at the same time, you can pipe to tr
to substitute arbitrary characters to the desired ones for display, before piping to a pager like less
if desired.
You can do it in a simpler way using the DialogResult.cancel
method.
Eg:
Dim anInput as String = InputBox("Enter your pin")
If anInput <>"" then
' Do something
Elseif DialogResult.Cancel then
Msgbox("You've canceled")
End if
Here is a way to do it with a closure:
def generate_add_mult_func(func):
def function_generator(x):
return reduce(func,range(1,x))
return function_generator
def add(x,y):
return x+y
def mult(x,y):
return x*y
adding=generate_add_mult_func(add)
multiplying=generate_add_mult_func(mult)
print adding(10)
print multiplying(10)
Here is a version with configurable parameters that you can set programmatically:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:param name="delim" select="','" />
<xsl:param name="quote" select="'"'" />
<xsl:param name="break" select="'
'" />
<xsl:template match="/">
<xsl:apply-templates select="projects/project" />
</xsl:template>
<xsl:template match="project">
<xsl:apply-templates />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$break" />
</xsl:if>
</xsl:template>
<xsl:template match="*">
<!-- remove normalize-space() if you want keep white-space at it is -->
<xsl:value-of select="concat($quote, normalize-space(), $quote)" />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$delim" />
</xsl:if>
</xsl:template>
<xsl:template match="text()" />
</xsl:stylesheet>
This is very common error that we face while starting any Project Vue. I spent lot of time to search this error and finally found a Solution. Suppose i have component that is "table.vue",
i.e components/table.vue
In app.js
Vue.component('mytablecomp', require('./components/table.vue').default);
So in in your index.blade file call component as
<mytablecomp></mytablecomp>
Just you need to keep in mind that your component name is in small not in large or camel case. Then my above code will surely work for you.
Thanks
var string = 'a,b,c,d',
strx = string.split(',');
array = [];
array = array.concat(strx);
// ["a","b","c","d"]
Followed by @Andy's answer, you can do following to solve your second question:
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
You can drop tables
by issuing an SQL Command as you would normally. If you want to drop the whole database you'll have to delete the file. You can delete the file located under
data/data/com.your.app.name/database/[databasefilename]
you can do this from the eclipse view called "FileBrowser" out of the "Android" Category for example. Or directly on your emulator or phone.
For Changing Year list item text color (SPECIFIC FOR ANDROID 5.0)
Just set certain text color in your date picker dialog style. For some reason setting flag yearListItemTextAppearance
doesn't reflect any change on year list.
<item name="android:textColor">@android:color/black</item>
SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'
select VALUE from TABLE1 where TIME =
(select max(TIME) from TABLE1 where DATE=
(select max(DATE) from TABLE1 where CRITERIA=CRITERIA))
Using ternary operator:
message = "blah" if 'key1' in dict else "booh"
print(message)
I had
tools:replace="android:allowBackup"
in my AndroidManifest.xml file.
I have got the exact information in merged manifest section.
After removing it the error got resolved.
There are no keys in JavaScript arrays. Use objects for that purpose.
var obj = {};
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
obj[news.title] = news.link;
});
});
// later:
$.each(obj, function (index, value) {
alert( index + ' : ' + value );
});
In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).
However, In your case it is not really clear to me why you transfer data from the original object (data.news
) at all. Why do you not simply pass a reference to that object around?
You can combine objects and arrays to achieve predictable iteration and key/value behavior:
var arr = [];
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
arr.push({
title: news.title,
link: news.link
});
});
});
// later:
$.each(arr, function (index, value) {
alert( value.title + ' : ' + value.link );
});
If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:
using System.Xml;
using System.Xml.Linq;
namespace www.dimaka.com
{
internal static class LinqHelper
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var reader = xDocument.CreateReader())
{
xmlDocument.Load(reader);
}
var xDeclaration = xDocument.Declaration;
if (xDeclaration != null)
{
var xmlDeclaration = xmlDocument.CreateXmlDeclaration(
xDeclaration.Version,
xDeclaration.Encoding,
xDeclaration.Standalone);
xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);
}
return xmlDocument;
}
}
}
Hope that helps!
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf
instead of System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}>
in the render function, and have to think around the problem.
Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body
, so even if it did work, your event handler would never trigger.
Instead, inside componentDidMount
somewhere in your application, you can listen to nv-enter by adding
document.body.addEventListener('nv-enter', function (event) {
// logic
});
Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.
Using NPM ( make sure that you have node version 8+ )
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
npm i @angular/cli --save
Using Yarn
yarn remove @angular/cli
yarn global add @angular/cli
yarn add @angular/cli
ng update @angular/cli
ng update @angular/core
ng update @angular/material
ng update rxjs
Normally that would mean that you have to update your code everywhere RxJS imports and operators are used, but thankfully there’s a package that takes care of most of the heavy lifting:
npm i -g rxjs-tslint
//or using yarn
yarn global add rxjs-tslint
Then you can run rxjs-5-to-6-migrate
rxjs-5-to-6-migrate -p src/tsconfig.app.json
finally remove rxjs-compat
npm uninstall rxjs-compat
// or using Yarn
yarn remove rxjs-compat
Refer to this link https://alligator.io/angular/angular-6/
So you have to manually update your package.json
file.
Then run
npm update
npm install --save rxjs-compat
npm i -g rxjs-tslint
rxjs-5-to-6-migrate -p src/tsconfig.app.json
Since you have your bgImage assigned and linked as an IBOutlet, there is no need to initialize it as a UIImageView... instead all you need to do is set the image property like bgImage.image = UIImage(named: "afternoon")
. After running this code, the image appeared fine since it was already assigned using the outlet.
However, if it wasn't an outlet and you didn't have it already connected to a UIImageView object on a storyboard/xib file, then you could so something like the following...
class ViewController: UIViewController {
var bgImage: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
var image: UIImage = UIImage(named: "afternoon")!
bgImage = UIImageView(image: image)
bgImage!.frame = CGRectMake(0,0,100,200)
self.view.addSubview(bgImage!)
}
}
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
It is not listed as a function in dplyr (yet): http://cran.rstudio.org/web/packages/dplyr/dplyr.pdf
The function below works (almost) the same if you don't want to load both plyr and dplyr
rename <- function(dat, oldnames, newnames) {
datnames <- colnames(dat)
datnames[which(datnames %in% oldnames)] <- newnames
colnames(dat) <- datnames
dat
}
dat <- rename(mtcars,c("mpg","cyl"), c("mympg","mycyl"))
head(dat)
mympg mycyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Edit: The comment by Romain produces the following (note that the changes function requires dplyr .1.1)
> dplyr:::changes(mtcars, dat)
Changed variables:
old new
disp 0x108b4b0e0 0x108b4e370
hp 0x108b4b210 0x108b4e4a0
drat 0x108b4b340 0x108b4e5d0
wt 0x108b4b470 0x108b4e700
qsec 0x108b4b5a0 0x108b4e830
vs 0x108b4b6d0 0x108b4e960
am 0x108b4b800 0x108b4ea90
gear 0x108b4b930 0x108b4ebc0
carb 0x108b4ba60 0x108b4ecf0
mpg 0x1033ee7c0
cyl 0x10331d3d0
mympg 0x108b4e110
mycyl 0x108b4e240
Changed attributes:
old new
names 0x10c100558 0x10c2ea3f0
row.names 0x108b4bb90 0x108b4ee20
class 0x103bd8988 0x103bd8f58
The interface
keyword indicates that you are declaring a traditional interface class in Java.
The @interface
keyword is used to declare a new annotation type.
See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface
means.
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
Jim's answer to this question may help; I copy it here. Quoting Guido van Rossum:
First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:
(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
If I may offer some suggestions (two years later but hopefully helpful to future readers):
h2
element.ooooooooooooo
text.if/then/else
construct if using XSLT 2.0.<h2>
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">m</xsl:when>
<xsl:otherwise>d</xsl:otherwise>
</xsl:choose>
ooooooooooooo
</h2>
<h2>
<xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/>
ooooooooooooo
</h2>
Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.
Example given
df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE,
NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA,
TRUE), p1_3 = c(TRUE,
TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA,
FALSE, FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA,
FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA,
FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA,
FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE,
FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE,
FALSE, NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE,
FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE,
FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names =
c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6",
"p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names =
c(NA, -7L), class = "data.frame")
p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1 TRUE FALSE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE FALSE
2 FALSE TRUE TRUE NA NA NA NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE NA NA NA NA
4 NA NA NA FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE
5 TRUE FALSE NA TRUE FALSE FALSE NA TRUE FALSE FALSE NA
6 FALSE NA FALSE FALSE NA NA FALSE FALSE NA NA FALSE
7 NA TRUE TRUE NA TRUE TRUE TRUE NA TRUE TRUE TRUE
Then by running that: df * 1
all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).
> df*1
p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1 1 0 1 0 1 1 1 0 1 1 0
2 0 1 1 NA NA NA NA 0 0 0 0
3 0 0 0 0 0 0 0 NA NA NA NA
4 NA NA NA 0 1 1 1 0 0 0 0
5 1 0 NA 1 0 0 NA 1 0 0 NA
6 0 NA 0 0 NA NA 0 0 NA NA 0
7 NA 1 1 NA 1 1 1 NA 1 1 1
I do not know if it a total "safe" command, under all different conditions / dfs.
I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was
onClick = () => {
// do something to compute or go fetch
// the url we need from the server
const url = goComputeOrFetchURL();
// window.location forces the browser to prompt the user if they want to download it
window.location = url
}
render() {
return (
<Button onClick={ this.onClick } />
);
}
CC -Dprivate=public
"CC" is the command line compiler on the system I use. -Dfoo=bar
does the equivalent of #define foo bar
. So, this compilation option effectively changes all private stuff to public.
Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.
printf("%hhX", a);
In most cases you will want to set the minimum length as well to fill the second character with zeroes:
printf("%02hhX", a);
ISO/IEC 9899:201x says:
7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following
First of all, do a backup of your needed databases with mysqldump
Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).
In total, do this:
sudo service mysql stop #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql
All above commands in single line (just copy and paste):
sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql
In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:
public abstract class EO {
@Autowired
protected SmsNotificationService smsNotificationService;
@Autowired
protected SendEmailService sendEmailService;
...
protected abstract void executeOperation(GenericMessage gMessage);
}
public final class OperationsExecutor {
public enum OperationsType {
ENROLL, CAMPAIGN
}
private OperationsExecutor() {
}
public static Object delegateOperation(OperationsType type, Object obj)
{
switch(type) {
case ENROLL:
if (obj == null) {
return new EnrollOperation();
}
return EnrollOperation.validateRequestParams(obj);
case CAMPAIGN:
if (obj == null) {
return new CampaignOperation();
}
return CampaignOperation.validateRequestParams(obj);
default:
throw new IllegalArgumentException("OperationsType not supported.");
}
}
}
@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
@Override
public void executeOperation(GenericMessage genericMessage) {
LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
}
}
Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)**
annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.
<context:annotation-config />
<context:component-scan base-package="com.xyz" />
I also tried these other references to find a solution:
Please try using **@Configurable(dependencyCheck = true)**
and update this post, I might try helping you if you face any problems.
If you don't have a 'real' certificate (and thus using a self-signed one), in Firefox you can go to:
Options > Privacy & Security > (scroll to the bottom) View Certificates > Servers > Add Exception...
There, fill in the location, eg: https://www.myserver:myport
Short answer is:
junk$nm[junk$nm %in% "B"] <- "b"
Take a look at Index vectors in R Introduction (if you don't read it yet).
EDIT. As noticed in comments this solution works for character vectors so fail on your data.
For factor best way is to change level:
levels(junk$nm)[levels(junk$nm)=="B"] <- "b"
This also can happen just by having multiple supported frameworks defined in the app.config file and, forcing the app to run in a different .NET framework other than the one mentioned first in the app.config file.
And also this fires when you have both of the mentioned frameworks available in your system.
As a workaround, bring up the target framework you are going to use for the debugging up in the app.config
ex: if you trying to run in .NET 4, config file should have something similar to this,
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
In your form element add data-ajax="false"
. I had the same problem using jquery mobile.
@fork2x
I have tried like this .Please review and update me whether it is right approach or not.
#/bin/sh
function pause(){
read -p "$*"
}
file="./apptest.properties"
if [ -f "$file" ]
then
echo "$file found."
dbUser=`sed '/^\#/d' $file | grep 'db.uat.user' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
dbPass=`sed '/^\#/d' $file | grep 'db.uat.passwd' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`
echo database user = $dbUser
echo database pass = $dbPass
else
echo "$file not found."
fi
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
Do you use some AJAX framework? Using jQuery it would be:
$.getScript('script.js');
If you're not using any framework then see the answer by Harmen.
(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById()
doesn't work consistently on all browsers - see this answer for details.)
It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:
to dynamically load scripts. Those may be relevant to people reading this question.
See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.
I think this site has the solution, i will test it now. It Seems like facebook has changed the parameters of share.php so, in order to customize share window text and images you have to put parameters in a "p" array.
Check it out.
You should try this one.
var table = $('#example').DataTable();
table.columns.adjust().draw();
SELECT COUNT(*), table1.category_id, table2.category_name
FROM table1
INNER JOIN table2 ON table1.category_id=table2.category_id
WHERE table1.colour <> 'red'
GROUP BY table1.category_id, table2.category_name
2020 | SWIFT 5.1:
let url = URL(fileURLWithPath: "//Users/Me/Desktop/Doc.txt")
let a = String(describing: url) // "file:////Users/Me/Desktop/Doc.txt"
let b = "\(url)" // "file:////Users/Me/Desktop/Doc.txt"
let c = url.absoluteString // "file:////Users/Me/Desktop/Doc.txt"
let d = url.path // "/Users/Me/Desktop/Doc.txt"
BUT value of d
will be invisible due to debug process, so...
THE BEST SOLUTION:
let e = "\(url.path)" // "/Users/Me/Desktop/Doc.txt"
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Try this in your console:
javac {$PathToYourProyect}/*
If you also need any external library, try:
javac -cp {$PathToYourLibrary}.jar {$PathToYourProyect}/*
"A picture is worth a thousand words".
I have a simple example here, it's similar to your case.
string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc
This is what happened:
s1
and s2
variables reference to the same "abc"
string object."abc"
string object do not modify itself (to "def"
), but a new "def"
string object is created instead, and then s1
references to it.s2
still references to "abc"
string object, so that's the output.You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.
See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:
function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
// IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
for (var prop in obj) this[prop] = obj[prop];
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));
alert(fooJSON.test() ); //Prints 12
You don't need jQuery for this. Here's a simple working example:
<!DOCTYPE html>
<html>
<head>
<title>box-shadow-experiment</title>
<style type="text/css">
#box-shadow-div{
position: fixed;
width: 1px;
height: 1px;
border-radius: 100%;
background-color:black;
box-shadow: 0 0 10px 10px black;
top: 49%;
left: 48.85%;
}
</style>
<script type="text/javascript">
window.onload = function(){
var bsDiv = document.getElementById("box-shadow-div");
var x, y;
// On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
window.addEventListener('mousemove', function(event){
x = event.clientX;
y = event.clientY;
if ( typeof x !== 'undefined' ){
bsDiv.style.left = x + "px";
bsDiv.style.top = y + "px";
}
}, false);
}
</script>
</head>
<body>
<div id="box-shadow-div"></div>
</body>
</html>
I chose position: fixed;
so scrolling wouldn't be an issue.
You can use a container like so:
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
You must of course import java.awt.Color
for the red color constant.
'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:
$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.php/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
Try using the Intel X86 Atom Storage Image for a relatively faster boot up than using ARM based images when emulating the device.
Another thing to be taken into the notice is that according to your system configuration, running an Android emulator with 1.21 GB RAM can be a sluggish experience, because the emulator requires up to some certain percentage of RAM which is used for emulating the device, not forgetting about the RAM used by the ADT.
Try a system image of 2.1 - 2.3.3 for at least a runnable experience. Plus not forgetting about Save to Snapshot for quicker loading. Though the first load may take time. But saving to a snapshot definitely saves up some time.
The simple solution using geom_abline
:
geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])
Where data.lm
is an lm
object, and coef(data.lm)
looks something like this:
> coef(data.lm)
(Intercept) DepDelay
-2.006045 1.025109
The numeric indexing assumes that (Intercept)
is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.
Well I think you just need to add a quantifier to each pattern. Also the carriage-return thing is a little funny:
text.replace(/[^a-z0-9]+|\s+/gmi, " ");
edit The \s
thing matches \r
and \n
too.
This seems to have worked for us.
history.pushState(null, null, $(location).attr('href'));
window.addEventListener('popstate', function () {
history.pushState(null, null, $(location).attr('href'));
});
Verifying ele is visible.
public static boolean isElementVisible(final By by)
throws InterruptedException {
boolean value = false;
if (driver.findElements(by).size() > 0) {
value = true;
}
return value;
}
If you have to send a multipart file that is composed, among other things, by an Object that needs to be converted with a specific HttpMessageConverter and you get the "no suitable HttpMessageConverter" error no matter what you try, you may want to try with this:
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter converter = new FormHttpMessageConverter();
converter.addPartConverter(new TheRequiredHttpMessageConverter());
//for example, in my case it was "new MappingJackson2HttpMessageConverter()"
restTemplate.getMessageConverters().add(converter);
This solved the problem for me with a custom Object that, together with a file (instanceof FileSystemResource, in my case), was part of the multipart file I needed to send. I tried with TrueGuidance's solution (and many others found around the web) to no avail, then I looked at FormHttpMessageConverter's source code and tried this.
WARNING: Do not run this on a production machine.
On a Linux box:
redis-cli KEYS "*" | wc -l
Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.
In excel 2013 the object creation string is:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
instead of the code in the answer above:
Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If you use an observable instead of a primitive value, the select will not raise change events on initial binding. You can continue to bind to the change event, rather than subscribing directly to the observable.
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
Another option is to let tkinter execute on a separate thread. One way of doing it is like this:
import Tkinter
import threading
class MyTkApp(threading.Thread):
def __init__(self):
self.root=Tkinter.Tk()
self.s = Tkinter.StringVar()
self.s.set('Foo')
l = Tkinter.Label(self.root,textvariable=self.s)
l.pack()
threading.Thread.__init__(self)
def run(self):
self.root.mainloop()
app = MyTkApp()
app.start()
# Now the app should be running and the value shown on the label
# can be changed by changing the member variable s.
# Like this:
# app.s.set('Bar')
Be careful though, multithreaded programming is hard and it is really easy to shoot your self in the foot. For example you have to be careful when you change member variables of the sample class above so you don't interrupt with the event loop of Tkinter.
Input these code to your SCRATCHPAD and see the action.
var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
Do the following:
<html>
)This is a hacky way, but it's the easiest way to do this.
I would like to add a 3rd Scenario
The moving position is not saved in any way. Think of it as a mouse movement - your cursor is not a React-component, right?
All you do, is to add a prop like "draggable" to your component and a stream of the dragging events that will manipulate the dom.
setXandY: function(event) {
// DOM Manipulation of x and y on your node
},
componentDidMount: function() {
if(this.props.draggable) {
var node = this.getDOMNode();
dragStream(node).onValue(this.setXandY); //baconjs stream
};
},
In this case, a DOM manipulation is an elegant thing (I never thought I'd say this)
This service returns Countries (name,code) and cities for any country as REST, SErvice. You can also download database and sample REST service
http://tecorange.com/content/world-countries-and-cities-restjson-service-12-months-subscription
There is a very flaky coverage of the LIKE operator for dates in SQL Server. It only works using American date format. As an example you could try:
... WHERE register_date LIKE 'oct 10 2009%'
I've tested this in SQL Server 2005 and it works, but you'll really need to try different combinations. Odd things I have noticed are:
You only seem to get all or nothing for different sub fields within the date, for instance, if you search for 'apr 2%' you only get anything in the 20th's - it omits 2nd's.
Using a single underscore '_' to represent a single (wildcard) character does not wholly work, for instance, WHERE mydate LIKE 'oct _ 2010%'
will not return all dates before the 10th - it returns nothing at all, in fact!
The format is rigid American: 'mmm dd yyyy hh:mm
'
I have found it difficult to nail down a process for LIKEing seconds, so if anyone wants to take this a bit further, be my guest!
Hope this helps.
You can read a file to have an RDD and then assign schema to it. Two common ways to creating schema are either using a case class or a Schema object [my preferred one]. Follows the quick snippets of code that you may use.
Case Class approach
case class Test(id:String,name:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()
Schema Approach
import org.apache.spark.sql.types._
val schemaString = "id name"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)
val dfWithSchema = sparkSess.read.option("header","false").schema(schema).csv("file.txt")
dfWithSchema.show()
The second one is my preferred approach since case class has a limitation of max 22 fields and this will be a problem if your file has more than 22 fields!
Here's another converted to Ruby code:
include Math
#Note: from/to = [lat, long]
def get_distance_in_km(from, to)
radians = lambda { |deg| deg * Math.PI / 180 }
radius = 6371 # Radius of the earth in kilometer
dLat = radians[to[0]-from[0]]
dLon = radians[to[1]-from[1]]
cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)
c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product))
return radius * c # Distance in kilometer
end
You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.
Rows("52:55").EntireRow.Hidden = False
becomes
activesheet.Rows("52:55").EntireRow.Hidden = False
i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,
Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub
That's it. Anytime you change something, it will run the macro test1.
C# 8 allows you to solve this problem elegantly and compactly using an switch expression:
public string GetTypeName(object obj)
{
return obj switch
{
int i => "Int32",
string s => "String",
{ } => "Unknown",
_ => throw new ArgumentNullException(nameof(obj))
};
}
As a result, you get:
Console.WriteLine(GetTypeName(obj: 1)); // Int32
Console.WriteLine(GetTypeName(obj: "string")); // String
Console.WriteLine(GetTypeName(obj: 1.2)); // Unknown
Console.WriteLine(GetTypeName(obj: null)); // System.ArgumentNullException
You can read more about the new feature here.
To access the index in this case you access the name
attribute:
In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
Note that if this is really what you are trying to do that the following works and is much faster:
In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop
EDIT
Looking at this question 3+ years later, you could just do:
In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
but assuming it isn't as trivial as this, whatever your rowFunc
is really doing, you should look to use the vectorised functions, and then use them against the df index:
In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
For type
public class KeyValue
{
public string KeyCol { get; set; }
public string ValueCol { get; set; }
}
collection
var wordList = new Model.DTO.KeyValue[] {
new Model.DTO.KeyValue {KeyCol="key1", ValueCol="value1" },
new Model.DTO.KeyValue {KeyCol="key2", ValueCol="value1" },
new Model.DTO.KeyValue {KeyCol="key3", ValueCol="value2" },
new Model.DTO.KeyValue {KeyCol="key4", ValueCol="value2" },
new Model.DTO.KeyValue {KeyCol="key5", ValueCol="value3" },
new Model.DTO.KeyValue {KeyCol="key6", ValueCol="value4" }
};
our linq query look like below
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList() };
or for array instead of list like below
var query =from m in wordList group m.KeyCol by m.ValueCol into g
select new { Name = g.Key, KeyCols = g.ToList().ToArray<string>() };
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.
Read more about the password file here.
Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.
Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.
For the odd positions, you probably want:
>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.which == 13) {
e.preventDefault();
return false;
}
});
This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.
Try using flex:
Plunker demo : https://plnkr.co/edit/nk02ojKuXD2tAqZiWvf9
/* Styles go here */
html,
body {
margin: 0;
padding: 0;
}
.container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 100vh;
grid-gap: 0px 0px;
}
.left_bg {
background-color: #3498db;
grid-column: 1 / 1;
grid-row: 1 / 1;
z-index: 0;
display: flex;
justify-content: center;
align-items: center;
}
.right_bg {
background-color: #ecf0f1;
grid-column: 2 / 2;
grid_row: 1 / 1;
z-index: 0;
display: flex;
justify-content: center;
align-items: center;
}
.text {
font-family: Raleway;
font-size: large;
text-align: center;
}
HTML
<div class="container">
<!--everything on the page-->
<div class="left_bg">
<!--left background color of the page-->
<div class="text">
<!--left side text content-->
<p>Review my stuff</p>
</div>
</div>
<div class="right_bg">
<!--right background color of the page-->
<div class="text">
<!--right side text content-->
<p>Hire me!</p>
</div>
</div>
</div>
In TSQL/MSSQL it looks like:
SELECT t.name, c.name
FROM sys.tables t
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types y ON y.user_type_id = c.user_type_id
WHERE t.name = ''
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
If you're using AMD modules, the other answers won't work in TypeScript 1.0 (the newest at the time of writing.)
You have different approaches available to you, depending upon how many things you wish to export from each .ts
file.
Foo.ts
export class Foo {}
export interface IFoo {}
Bar.ts
import fooModule = require("Foo");
var foo1 = new fooModule.Foo();
var foo2: fooModule.IFoo = {};
Foo.ts
class Foo
{}
export = Foo;
Bar.ts
import Foo = require("Foo");
var foo = new Foo();
PYTHONPATH
is an environment variable/usr/lib/python2.7
on UbuntuPYTHONPATH
explicitlyIf you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.
Not sure why, but '{:0.2f}'.format(0.5357706) gives me '0.54'. The only solution that works for me (python 3.6) is the following:
def ceil_floor(x):
import math
return math.ceil(x) if x < 0 else math.floor(x)
def round_n_digits(x, n):
import math
return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)
round_n_digits(-0.5357706, 2) -> -0.53
round_n_digits(0.5357706, 2) -> 0.53
Here is a solution with jQuery that works like a charm. It checks if the height of the window is greater than the height of the body. If it is, then it changes the margin-top of the footer to compensate. Tested in Firefox, Chrome, Safari and Opera.
$( function () {
var height_diff = $( window ).height() - $( 'body' ).height();
if ( height_diff > 0 ) {
$( '#footer' ).css( 'margin-top', height_diff );
}
});
If your footer already has a margin-top (of 50 pixels, for example) you will need to change the last part for:
css( 'margin-top', height_diff + 50 )
In the case of a printer friendly stylesheet, I use the following:
/* screen style */
.print_only { display: none; }
/* print stylesheet */
div.print_only { display: block; }
span.print_only { display: inline; }
.no_print { display: none; }
I used this when I needed to print a form containing values and the input fields were difficult to print. So I added the values wrapped in a span.print_only tag (div.print_only was used elsewhere) and then applied the .no_print class to the input fields. So on-screen you would see the input fields and when printed, only the values. If you wanted to get fancy you could use JS to update the values in the span tags when the fields were updated but that wasn't necessary in my case. Perhaps not the the most elegant solution but it worked for me!
I have found a pretty big difference in timing when testing in my browser.
I used the following script:
WARNING: running this will freeze your browser a bit, might even crash it.
var n = 10000000, i;_x000D_
i = n;_x000D_
console.time('selector');_x000D_
while (i --> 0){_x000D_
$("body");_x000D_
}_x000D_
_x000D_
console.timeEnd('selector');_x000D_
_x000D_
i = n;_x000D_
console.time('element');_x000D_
while (i --> 0){_x000D_
$(document.body);_x000D_
}_x000D_
_x000D_
console.timeEnd('element');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I did 10 million interactions, and those were the results (Chrome 65):
selector: 19591.97509765625ms
element: 4947.8759765625ms
Passing the element directly is around 4 times faster than passing the selector.
For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.
You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php
The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.
That's all it is.
public class SingletonExample { private static SingletonExample instance = null; private static int value = 0; private SingletonExample() { ++this.value; } public static SingletonExample getInstance() { if(instance!=null) return instance; synchronized(SingletonExample.class) { instance = new SingletonExample(); return instance; } } public void printValue() { System.out.print( this.value ); } public static void main(String [] args) { SingletonExample instance = getInstance(); instance.printValue(); instance = getInstance(); instance.printValue(); } }
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
There is many way to watch multiple values :
//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
// do what you want here
});
or more recent version
//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
//do what you want here
});
Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope
try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags
/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
Give your two buttons the same name and different values:
<input type="submit" name="submit_button" value="Do Something">
<input type="submit" name="submit_button" value="Do Something Else">
Then in your Flask view function you can tell which button was used to submit the form:
def contact():
if request.method == 'POST':
if request.form['submit_button'] == 'Do Something':
pass # do something
elif request.form['submit_button'] == 'Do Something Else':
pass # do something else
else:
pass # unknown
elif request.method == 'GET':
return render_template('contact.html', form=form)
Requirements:
Code:
import pandas as pd
from sqlalchemy import create_engine
SECRET = {'username':'lol', 'password': 'lol'}
user_name = SECRET.get('username')
passwd = SECRET.get('password')
host_server = 'x.x.x.x'
port = '10000'
database = 'default'
conn = f'hive://{user_name}:{passwd}@{host_server}:{port}/{database}'
engine = create_engine(conn, connect_args={'auth': 'LDAP'})
query = "select * from tablename limit 100"
data = pd.read_sql(query, con=engine)
print(data)
true
or if its empty.The method empty?
comes from the Array class
http://ruby-doc.org/core-2.0.0/Array.html#method-i-empty-3F
It's used to check if the array contains something or not. This includes things that evaluate to false
, such as nil
and false
.
>> a = []
=> []
>> a.empty?
=> true
>> a = [nil, false]
=> [nil, false]
>> a.empty?
=> false
>> a = [nil]
=> [nil]
>> a.empty?
=> false
The method any?
comes from the Enumerable module.
http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-any-3F
It's used to evaluate if "any" value in the array evaluates to true
.
Similar methods to this are none?
, all?
and one?
, where they all just check to see how many times true could be evaluated. which has nothing to do with the count of values found in a array.
case 1
>> a = []
=> []
>> a.any?
=> false
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> true
case 2
>> a = [nil, true]
=> [nil, true]
>> a.any?
=> true
>> a.one?
=> true
>> a.all?
=> false
>> a.none?
=> false
case 3
>> a = [true, true]
=> [true, true]
>> a.any?
=> true
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> false
Use fallocate
if you don't want to wait for disk.
Example:
fallocate -l 100G BigFile
Usage:
Usage:
fallocate [options] <filename>
Preallocate space to, or deallocate space from a file.
Options:
-c, --collapse-range remove a range from the file
-d, --dig-holes detect zeroes and replace with holes
-i, --insert-range insert a hole at range, shifting existing data
-l, --length <num> length for range operations, in bytes
-n, --keep-size maintain the apparent size of the file
-o, --offset <num> offset for range operations, in bytes
-p, --punch-hole replace a range with a hole (implies -n)
-z, --zero-range zero and ensure allocation of a range
-x, --posix use posix_fallocate(3) instead of fallocate(2)
-v, --verbose verbose mode
-h, --help display this help
-V, --version display version
Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:
void somefunc(int a)
{
if (a == 1)
goto label1;
if (a == 2)
goto label2;
label1:
...
label2:
...
}
Could be done in python like this:
def func1():
...
def func2():
...
funcmap = {1 : func1, 2 : func2}
def somefunc(a):
funcmap[a]() #Ugly! But it works.
Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.
@ascobol:
Your best bet is to either enclose it in a function or use an exception. For the function:
def loopfunc():
while 1:
while 1:
if condition:
return
For the exception:
try:
while 1:
while 1:
raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
pass
Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)
Here you go with modified data.json
file:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [{
"id": "valore"
}],
"om_points": "value",
"parameters": [{
"id": "valore"
}]
}
You can call or print data on console by using below lines:
import json
from pprint import pprint
with open('data.json') as data_file:
data_item = json.load(data_file)
pprint(data_item)
Expected output for print(data_item['parameters'][0]['id'])
:
{'maps': [{'id': 'blabla', 'iscategorical': '0'},
{'id': 'blabla', 'iscategorical': '0'}],
'masks': [{'id': 'valore'}],
'om_points': 'value',
'parameters': [{'id': 'valore'}]}
Expected output for print(data_item['parameters'][0]['id'])
:
valore
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
To display only running containers
docker ps
To show all containers (includes all states)
docker ps -a
To show the latest created container (includes all states)
docker ps -l
To show n last created containers (includes all states)
docker ps -n=-1
To display total file sizes
docker ps -s
In the new version of Docker, commands are updated, and some management commands are added:
docker container ls
List all the running containers.
docker container ls -a
I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/
Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.
Be aware that the timeout time is in seconds.
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
Make sure the header files are publicly available as part of the framework's public headers.
Goto Framework -> Target -> Build Phases and drag to move the relevant header files from Project to Public. Hope that helps!
The normal idea would be to run the command and then use $?
to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.
ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.
I personally like to put this function in my .bashrc
file
Below I demonstrate a few ways in which you can use this:
# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.
$ ec echo test
test
$ echo $ec
0
# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.
$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0
# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`
$ ec -h echo test
$ echo $ec
0
Solution to your code using this function
#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
echo "Error when executing command: 'grep p' [$ec]"
exit $ec;
fi
You should also note that the exit code you will be seeing will be for the
grep
command that's being run, as it is the last command being executed. Not thels
.
Using refs
is not best practice because it reads the DOM directly, it's better to use React's state
instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
You can use setState
together with an onChange
event listener to render the component again every time the input field changes:
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
Here's a working example:
class AddItem extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { value: '' };_x000D_
this.onChange = this.onChange.bind(this);_x000D_
this.add = this.add.bind(this);_x000D_
}_x000D_
_x000D_
add() {_x000D_
this.props.onButtonClick(this.state.value);_x000D_
this.setState({ value: '' });_x000D_
}_x000D_
_x000D_
onChange(e) {_x000D_
this.setState({ value: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div className="add-item">_x000D_
<input_x000D_
type="text"_x000D_
className="add-item__input"_x000D_
value={this.state.value}_x000D_
onChange={this.onChange}_x000D_
placeholder={this.props.placeholder}_x000D_
/>_x000D_
<button_x000D_
disabled={!this.state.value}_x000D_
className="add-item__button"_x000D_
onClick={this.add}_x000D_
>_x000D_
Add_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
I would think that one reason could be that the color is applied to things other than font. For example:
div {
border: 1px solid;
color: red;
}
Yields both a red font color and a red border.
Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.
If you're using VS Express 2015, just go to your control panel --> programs and features --> select vs 2015 --> click change, then in the VS Express installer select 'Modify' --> select Publishing tools, and finish. Once setup completes the changes you will be able to create your installer.
Null signifies and absence of data, that is it is unknown, not a data value of nothing. It's very easy for people from a programming background to confuse this because in C type languages when using pointers null is indeed nothing.
Hence in the first case 3 is indeed in the set of (1,2,3,null) so true is returned
In the second however you can reduce it to
select 'true' where 3 not in (null)
So nothing is returned because the parser knows nothing about the set to which you are comparing it - it's not an empty set but an unknown set. Using (1, 2, null) doesn't help because the (1,2) set is obviously false, but then you're and'ing that against unknown, which is unknown.
implementation 'com.android.support:appcompat-v7:28.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
All to add
See my comment above asking for clarification on what you really want. Hopefully this is it:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;
I had the same problem when trying to run a PowerShell script that only looked at a remote server to read the size of a hard disk.
I turned off the Firewall (Domain networks, Private networks, and Guest or public network) on the remote server and the script worked.
I then turned the Firewall for Domain networks back on, and it worked.
I then turned the Firewall for Private network back on, and it also worked.
I then turned the Firewall for Guest or public networks, and it also worked.
To get all the counts for all the columns in a dataframe, it's just df.count()
I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database
The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second
. It also has a STOP button:
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
if(hour < 10)
hour = "0"+hour;
if(minute < 10)
minute = "0"+minute;
if(seconds < 10)
seconds = "0"+seconds;
document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
_x000D_
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
_x000D_
Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:
$
and jQuery
belong to versionX.$
and jQuery
belong to versionY, plus _$
and _jQuery
belong to versionX.my_jQuery = jQuery.noConflict(true);
-- now $
and jQuery
belong to versionX, _$
and _jQuery
are probably null, and my_jQuery
is versionY.to print all (or arbitrarily many) lines of the grouped df:
import pandas as pd
pd.set_option('display.max_rows', 500)
grouped_df = df.group(['var1', 'var2'])
print(grouped_df)
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
If it's only one line of text you could use the line-height property, with the same value as the element height:
height:100px;
line-height:100px;
If the text has multiple lines, or if the content is variable, you could use the padding-top:
padding-top:30px;
height:70px;
Example: http://jsfiddle.net/2GUFL/
Dougs answer is correct, but you actually can use $.getJSON
and catch errors (not having to use $.ajax
). Just chain the getJSON
call with a call to the fail
function:
$.getJSON('/foo/bar.json')
.done(function() { alert('request successful'); })
.fail(function() { alert('request failed'); });
Live demo: http://jsfiddle.net/NLDYf/5/
This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.
Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/
Something like this should work:
var dropdown = document.getElementById("dropdown1");
if (dropdown) {
for (var i=0; i < month.length;++i){
addOption(dropdown, month[i], month[i]);
}
}
addOption = function(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
You can refer to this article for more details:
http://www.plus2net.com/javascript_tutorial/list-adding.php
I had a similar error, which was fixed by adding:
Options FollowSymLinks
... in the apps/[app-name]/conf/httpd-app.conf
file. This is because, in my case, an .htaccess
file wants to use rewrite rules, that are not allowed with FollowSymLinks AND SymLinksIfOwnerMatch turned off.
If your conf file already has a line with Options ...
, you can just add FollowSymLinks
to the list of options. You could end up with something like this:
Options Indexes MultiViews FollowSymLinks
categories_posts
and categories_news
start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique
starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:
SELECT *
FROM developer_configurations_cms
WHERE developer_configurations_cms.cat_id = '1'
AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'
You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:
Obj.prototype.toString= function(){
var A= [];
for(var p in this){
if(this.hasOwnProperty(p)){
A[A.length]= p+'='+this[p];
}
}
return A.join(', ');
}
This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.
Apply
startActivity(new Intent(FirstActivity.this,SecondActivity.class));
then
overridePendingTransition(0, 0);
This will stop the animation.
Use num_holes=None
as a default, instead. Then check for whether num_holes is None
, and if so, randomize. That's what I generally see, anyway.
More radically different construction methods may warrant a classmethod that returns an instance of cls
.
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
git status #then file which you need to push git add example.FileExtension
git commit "message is example"
git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)
There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.
Alternatively you can install a specialized file compare software like WinMerge.
Unfortunately, there is no good, portable way to do this that I know of. If you attempt to parse /etc/group, as others are suggesting, you will miss users who have that group as their primary group and anyone who has been added to that group via a mechanism other than UNIX flat files (i.e. LDAP, NIS, pam-pgsql, etc.).
If I absolutely had to do this myself, I'd probably do it in reverse: use id
to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.
Edit: Of course, this leaves you with a similar problem: how to get a list of every user on the system. Since my location uses only flat files and LDAP, I can just get a list from both locations, but that may or may not be true for your environment.
Edit 2: Someone in passing reminded me that getent passwd
will return a list of all users on the system including ones from LDAP/NIS/etc., but getent group
still will still miss users that are members only via the default group entry, so that inspired me to write this quick hack.
#!/usr/bin/perl -T
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Copyright © 2010-2013 by Zed Pobre ([email protected] or [email protected])
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
use strict; use warnings;
$ENV{"PATH"} = "/usr/bin:/bin";
my $wantedgroup = shift;
my %groupmembers;
my $usertext = `getent passwd`;
my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
foreach my $userid (@users)
{
my $usergrouptext = `id -Gn $userid`;
my @grouplist = split(' ',$usergrouptext);
foreach my $group (@grouplist)
{
$groupmembers{$group}->{$userid} = 1;
}
}
if($wantedgroup)
{
print_group_members($wantedgroup);
}
else
{
foreach my $group (sort keys %groupmembers)
{
print "Group ",$group," has the following members:\n";
print_group_members($group);
print "\n";
}
}
sub print_group_members
{
my ($group) = @_;
return unless $group;
foreach my $member (sort keys %{$groupmembers{$group}})
{
print $member,"\n";
}
}
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
try this jquery library, jQuery Print Element
http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
Starting from CSS Selectors 4 using multiple arguments in the :not
selector becomes possible (see here).
In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.
Example:
/* In this example, all p elements will be red, except for
the first child and the ones with the class special. */
p:not(:first-child, .special) {
color: red;
}
Unfortunately, browser support is limited. For now, it only works in Safari.
Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").
I think you are looking for $evalAsync http://docs.angularjs.org/api/ng.$rootScope.Scope#$evalAsync
Kibana 4 logs to stdout
by default. Here is an excerpt of the config/kibana.yml
defaults:
# Enables you specify a file where Kibana stores log output.
# logging.dest: stdout
So when invoking it with service
, use the log capture method of that service. For example, on a Linux distribution using Systemd / systemctl (e.g. RHEL 7+):
journalctl -u kibana.service
One way may be to modify init scripts to use the --log-file
option (if it still exists), but I think the proper solution is to properly configure your instance YAML file. For example, add this to your config/kibana.yml
:
logging.dest: /var/log/kibana.log
Note that the Kibana process must be able to write to the file you specify, or the process will die without information (it can be quite confusing).
As for the --log-file
option, I think this is reserved for CLI operations, rather than automation.
You must use the global
declaration when you wish to alter the value assigned to a global variable.
You do not need it to read from a global variable. Note that calling a method on an object (even if it alters the data within that object) does not alter the value of the variable holding that object (absent reflective magic).
A simple string.Concat() is what you need.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = string.Concat(test);
If you also need to add a seperator (space, comma etc) then, string.Join() should be used.
string[] test = new string[2];
test[0] = "Red";
test[1] = "Blue";
string result = string.Join(",", test);
If you have to perform this on a string array with hundereds of elements than string.Join() is better by performace point of view. Just give a "" (blank) argument as seperator. StringBuilder can also be used for sake of performance, but it will make code a bit longer.
Try excluding height from the style element.
i.e. neither give height:100% nor to any other value.
You can see this solution. It shows how to get/set cookies, but cookies are just one of the headers in a request/response. You have to override one of the Volley's *Request classes and set the required headers in getHeaders()
Here is the linked source:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* @param method
* @param url
* @param params
* A {@link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* @param listener
* @param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
@Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* @see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
And MyApp class:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
@Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* @param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* @param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
Just pass UTC date format from your server side code to client side
and use below syntax -
{{dateUTCField +'Z' | date : 'mm/dd/yyyy'}}
e.g. dateUTCField = '2018-01-09T10:02:32.273' then it display like 01/09/2018
This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *
First two answers here: How to enable CORS in AngularJs
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
run sbt console then type sbtVersion
to check sbt version, and scalaVersion
for scala version
string
does not name a type. The class in the string
header is called std::string
.
Please do not put using namespace std
in a header file, it pollutes the global namespace for all users of that header. See also "Why is 'using namespace std;' considered a bad practice in C++?"
Your class should look like this:
#include <string>
class Game
{
private:
std::string white;
std::string black;
std::string title;
public:
Game(std::istream&, std::ostream&);
void display(colour, short);
};
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
You can only have one primary key, but you can have multiple columns in your primary key.
You can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
Cursors make people overly apply a procedural mindset to a set-based environment.
And they are SLOW!!!
From SQLTeam:
Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.
Try this code
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0){
$('.sendButton').attr('disabled', false);
}
else
{
$('.sendButton').attr('disabled', true);
}
})
});
Check demo Fiddle
You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()
after val
function in if($(this).val.length !=0){
I think the closest collection you'll get from the framework is the SortedMap
I am using as what John Rasch said:
Stream streamContent = taxformUpload.FileContent;
There is a situation where the dot operator will give different answers when dealing with arrays as with dealing with matrices. For example, suppose the following:
>>> a=numpy.array([1, 2, 3])
>>> b=numpy.array([1, 2, 3])
Lets convert them into matrices:
>>> am=numpy.mat(a)
>>> bm=numpy.mat(b)
Now, we can see a different output for the two cases:
>>> print numpy.dot(a.T, b)
14
>>> print am.T*bm
[[1. 2. 3.]
[2. 4. 6.]
[3. 6. 9.]]
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center
let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes: [.font: titleFont,
.foregroundColor: UIColor.red,
.paragraphStyle: titleParagraphStyle])
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center
let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes: [NSFontAttributeName:titleFont,
NSForegroundColorAttributeName:UIColor.red,
NSParagraphStyleAttributeName: titleParagraphStyle])
(original answer below)
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center
let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes:[NSFontAttributeName:titleFont,
NSForegroundColorAttributeName:UIColor.redColor(),
NSParagraphStyleAttributeName: titleParagraphStyle])
You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)
This jar is used for XML binding which is applicable for .xlsx files.
Just modified @ClickUpvote's answer:
You can use IIFE (Immediately Invoked Function Expression) and recursion to make it a little bit more easier:
var i = 5; //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs'); //do stuff here
timer();
}, 1000);
})();
var i = 5;_x000D_
(function timer(){_x000D_
if (--i < 0) return;_x000D_
setTimeout(function(){_x000D_
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';_x000D_
timer();_x000D_
}, 1000);_x000D_
})();
_x000D_
<h1>5 secs</h1>
_x000D_
If you use the Mongoose API and looking to pull a sub/child object: Read this document Don't forget to use save() when you're done editing otherwise the changes won't be saved to the database.
//just edit menu.xml file
//add icon for item which will change default setting icon
//add sub menus
///menu.xml file
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:icon="@drawable/your_icon"
app:showAsAction="always" >
<menu>
<item android:id="@+id/action_menu1"
android:icon="@android:drawable/ic_menu_preferences"
android:title="menu 1" />
<item android:id="@+id/action_menu2"
android:icon="@android:drawable/ic_menu_help"
android:title="menu 2" />
</menu>
</item>
Please try the following code snippet,
IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value),
Format(Avg(Fields!Vision_Score.Value)),
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))
hope it will help, Thank-you.