First off, you should realize that you don't actually need to use HTML entities – as long as your HTML document's encoding is declared properly as UTF-8, you can simply copy/paste these symbols into your file/server-side script/JavaScript/whatever.
Having said that, here's the exhaustive list of all relevant UTF-8 characters / HTML entities related to this topic:
☐
/ dec: ☐
): ballot box (empty, that's how it's supposed to be)☑
/ dec: ☑
): ballot box with check☒
/ dec: ☒
): ballot box with x✓
/ dec: ✓
): check mark, equivalent to ✓
and ✓
in most browsers✔
/ dec: ✔
): heavy check mark✗
/ dec: ✗
): ballot x✘
/ dec: ✘
): heavy ballot x🗸
/ dec 🗸
): light check mark (poorly supported as of 2017)✅
/ dec: ✅
): white heavy check mark (mixed support as of 2017)🗴
/ dec: 🗴
): ballot script X (poorly supported as of 2017)🗶
/ dec: 🗶
): ballot bold script X (poorly supported as of 2017)⮽
/ dec: ⮽
): ballot box with light X (poorly supported as of 2017)🗵
/ dec: 🗵
): ballot box with script X (poorly supported as of 2017)🗹
/ dec: 🗹
): ballot box with bold check (poorly supported as of 2017)🗷
/ dec: 🗷
): ballot box with bold script X (poorly supported as of 2017)Checking out web fonts for tick symbols? Here's a ready to use sample for the more common ones: A?B?C?D?E?F?G?H
-- just copy/paste this into your webfont provider's sample text box and see which fonts support what tick symbols.
As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:
The Code below checks if the key 'A' is down.
if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
// Do stuff
}
In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx
if(GetKeyState(VK_SHIFT) & 0x8000)
{
// Shift down
}
The low-order bit indicates if key is toggled.
SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;
Oh and also don't forget to
#include <Windows.h>
socket.isConnected()
returns always true once the client connects (and even after the disconnect) weird !!socket.getInputStream().read()
returns -1
if the client disconnectedsocket.getInetAddress().isReachable(int timeout)
: From isReachable(int timeout)
Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:
Prefs > Package Control
. Here you can install, remove or see a list of all installed packages.Prefs > Package Settings
. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.From http://www.dotnetperls.com:
7z a secure.7z * -pSECRET
Where:
7z : name and path of 7-Zip executable
a : add to archive
secure.7z : name of destination archive
* : add all files from current directory to destination archive
-pSECRET : specify the password "SECRET"
To open :
7z x secure.7z
Then provide the SECRET password
Note: If the password contains spaces or special characters, then enclose it with single quotes
7z a secure.7z * -p"pa$$word @|"
Alas this works in Python 3 at least...
Python 3
Sometimes the error is in the enviroment variables and enconding so
import os
import locale
os.environ["PYTHONIOENCODING"] = "utf-8"
myLocale=locale.setlocale(category=locale.LC_ALL, locale="en_GB.UTF-8")
...
print(myText.encode('utf-8', errors='ignore'))
where errors are ignored in encoding.
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
If you want to add the absent serialVersionUID for a bunch of files, IntelliJ IDEA may not work very well. I come up some simple script to fulfill this goal with ease:
base_dir=$(pwd)
src_dir=$base_dir/src/main/java
ic_api_cp=$base_dir/target/classes
while read f
do
clazz=${f//\//.}
clazz=${clazz/%.java/}
seruidstr=$(serialver -classpath $ic_api_cp $clazz | cut -d ':' -f 2 | sed -e 's/^\s\+//')
perl -ni.bak -e "print $_; printf qq{%s\n}, q{ private $seruidstr} if /public class/" $src_dir/$f
done
You save this script, say as add_serialVersionUID.sh
in your ~/bin
folder. Then you run it in the root directory of your Maven or Gradle project like:
add_serialVersionUID.sh < myJavaToAmend.lst
This .lst includes the list of Java files to add the serialVersionUID in the following format:
com/abc/ic/api/model/domain/item/BizOrderTransDO.java
com/abc/ic/api/model/domain/item/CardPassFeature.java
com/abc/ic/api/model/domain/item/CategoryFeature.java
com/abc/ic/api/model/domain/item/GoodsFeature.java
com/abc/ic/api/model/domain/item/ItemFeature.java
com/abc/ic/api/model/domain/item/ItemPicUrls.java
com/abc/ic/api/model/domain/item/ItemSkuDO.java
com/abc/ic/api/model/domain/serve/ServeCategoryFeature.java
com/abc/ic/api/model/domain/serve/ServeFeature.java
com/abc/ic/api/model/param/depot/DepotItemDTO.java
com/abc/ic/api/model/param/depot/DepotItemQueryDTO.java
com/abc/ic/api/model/param/depot/InDepotDTO.java
com/abc/ic/api/model/param/depot/OutDepotDTO.java
This script uses the JDK serialVer tool. It is ideal for a situation when you want to amend a huge number of classes which had no serialVersionUID set in the first place while maintain the compatibility with the old classes.
Applying
<item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
in Theme.AppCompat.Light.DarkActionBar
didn't worked for me. What did the trick is , giving colorPrimaryDark
as usual along with android:colorPrimary
in styles.xml
<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>
and in setting
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
Window window = this.Window;
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
}
didn't had to set statusbar color in code .
You can try:
<label id ="label_id"></label>
$("#label_id").html('value');
The only thing that worked for me:
g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);
Using the AWS 'user data' and 'meta data' APIs its possible to write a script which wraps puppet to start a puppet run with a custom cert name.
First start an aws instance with custom user data: 'role:webserver'
#!/bin/bash
# Find the name from the user data passed in on instance creation
USER=$(curl -s "http://169.254.169.254/latest/user-data")
IFS=':' read -ra UDATA <<< "$USER"
# Find the instance ID from the meta data api
ID=$(curl -s "http://169.254.169.254/latest/meta-data/instance-id")
CERTNAME=${UDATA[1]}.$ID.aws
echo "Running Puppet for certname: " $CERTNAME
puppet agent -t --certname=$CERTNAME
This calls puppet with a certname like 'webserver.i-hfg453.aws' you can then create a node manifest called 'webserver' and puppets 'fuzzy node matching' will mean it is used to provision all webservers.
This example assumes you build on a base image with puppet installed etc.
Benefits:
1) You don't have to pass round your credentials
2) You can be as granular as you like with the role configs.
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.
You can declare multiple variables, and initialize multiple variables, but not both at the same time:
String one,two,three;
one = two = three = "";
However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".
abstract method do not have body.A well defined method can't be declared abstract.
A class which has abstract method must be declared as abstract.
Abstract class can't be instantiated.
If your file has a return statement like this:
<?php return array(
'AF' => 'Afeganistão',
'ZA' => 'África do Sul',
...
'ZW' => 'Zimbabué'
);
You can get this to a variable like this:
$data = include $filePath;
It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:
a.disabled {_x000D_
/* Make the disabled links grayish*/_x000D_
color: gray;_x000D_
/* And disable the pointer events */_x000D_
pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
I've been searching answer but couldn't find but finally I could fix this by adding play-service-ads
dependency let's try this:
*) File -> Project Structure... -> Under the module you can find app and there is a option called dependencies and you can add com.google.android.gms:play-services-ads:x.x.x dependency to your project
I faced this problem when I try to import Eclipse projects into Android Studio.
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
The key is a Textview with singleline=false
(which yes is deprecated, but is a must have to work) combined with lines
, maxlines
or minlines
<TextView
android:id="@+id/txtBowlers"
style="@style/Default_TextBox.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:singleLine="false"
android:maxLines="6"
android:text="Bob\nSally\nJohn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/txtTeamName"
app:layout_constraintTop_toBottomOf="@+id/txtTeamName"/>
the code can be used to sort string in alphabetical order without using any inbuilt function of python
k = input("Enter any string again ")
li = []
x = len(k)
for i in range (0,x):
li.append(k[i])
print("List is : ",li)
for i in range(0,x):
for j in range(0,x):
if li[i]<li[j]:
temp = li[i]
li[i]=li[j]
li[j]=temp
j=""
for i in range(0,x):
j = j+li[i]
print("After sorting String is : ",j)
Depends on your needs, if you know what parent your looking for you can use the .parents() selector.
E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/
<div id="One">
<div id="Two">
<div id="Three">
<div id="Four">
</div>
</div>
</div>
</div>
var top = $("#Four").parents("#One");
alert($(top).html());
Example using index:
//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);
alert($(topTwo ).html());
Syntax | Name | Description |
---|---|---|
x == y |
Equality | true if x and y have the same key/value pairs |
x != y |
Inequality | true if x is not equal to y |
x === y |
Identity | true if x and y have the same key/value pairsin the same order and of the same types |
x !== y |
Non-identity | true if x is not identical to y |
++x |
Pre-increment | Increments x by one, then returns x |
x++ |
Post-increment | Returns x, then increments x by one |
--x |
Pre-decrement | Decrements x by one, then returns x |
x-- |
Post-decrement | Returns x, then decrements x by one |
x and y |
And | true if both x and y are true . If x=6, y=3 then(x < 10 and y > 1) returns true |
x && y |
And | true if both x and y are true . If x=6, y=3 then(x < 10 && y > 1) returns true |
x or y |
Or | true if any of x or y are true . If x=6, y=3 then(x < 10 or y > 10) returns true |
x || y |
Or | true if any of x or y are true . If x=6, y=3 then(x < 3 || y > 1) returns true |
a . b |
Concatenation | Concatenate two strings: "Hi" . "Ha" |
For an array of objects you can create an extension from Sequence.
extension Sequence {
func limit(_ max: Int) -> [Element] {
return self.enumerated()
.filter { $0.offset < max }
.map { $0.element }
}
}
Usage:
struct Apple {}
let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)
// limitTwoApples: [Apple(), Apple()]
What I did to solve the problem was:
git pull origin [branch]
git push origin [branch]
Also make sure that you are pointing to the right branch by running:
git remote set-url origin [url]
Minimal runnable example
main.cpp
#include <cassert>
class C {
public:
int i;
C(int i) : i(i) {}
int m(int j) { return this->i + j; }
};
int main() {
// Get a method pointer.
int (C::*p)(int) = &C::m;
// Create a test object.
C c(1);
C *cp = &c;
// Operator .*
assert((c.*p)(2) == 3);
// Operator ->*
assert((cp->*p)(2) == 3);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Tested in Ubuntu 18.04.
You cannot change the order of the parenthesis or omit them. The following do not work:
c.*p(2)
c.*(p)(2)
GCC 9.2 would fail with:
main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
19 | assert(c.*p(2) == 3);
|
C++11 standard
.*
and ->*
are a single operators introduced in C++ for this purpose, and not present in C.
.*
and ->*
.It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
You could also do what I do and by a commercial control like this one: http://www.syncfusion.com/products/reporting-edition/xlsio
I have been struging for years before ending with a commercial solution. I first tried the OLEDB approach that is very easy to use in my development environment but can be a knightmare to deploy. Then I tried the open source solutions but most of the are outdated and have bad support.
The xlsio controls from syncfusion are just the ones I use and are happy with but others exists. If you can affort it, do not hesitate, it's the best solution. Why? Because it has no dependencies with the system and supports all version of office right away. Among other advantages like, it's really fast.
And no, I do not work for synfusion ;)
this will unhide all files and folders on your computer
attrib -r -s -h /S /D
try using the permission of WRITE_EXTERNAL_STORAGE You should use that whether there is an external card or not.
This works well for me:
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
File file = new File(path, "/" + fname);
and places my files in the appropriate folder
Note: using // at the beginning of the xpath is a bit CPU intensitve -- it will search every node for a match. Using a more specific path, such as /root/DataSet will create a faster query.
I think ResponseEntityExceptionHandler
meets your requirements. A sample piece of code for HTTP 400:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class,
HttpRequestMethodNotSupportedException.class})
public ResponseEntity<Object> badRequest(HttpServletRequest req, Exception exception) {
// ...
}
}
You can check this post
This is not directly to your code sample, but in general about the error. I'm writing it here, because Google directs this error to this question, so it may be useful for the other devs.
Another use case when you can receive such error is when you're adding a selector to method in another class, eg:
private class MockTextFieldTarget {
private(set) var didCallDoneAction = false
@objc func doneActionHandler() {
didCallDoneAction = true
}
}
And then in another class:
final class UITextFieldTests: XCTestCase {
func testDummyCode() {
let mockTarget = MockTextFieldTarget()
UIBarButtonItem(barButtonSystemItem: .cancel, target: mockTarget, action: MockTextFieldTarget.doneActionHandler)
// ... do something ...
}
}
If in the last line you'd simply call #selector(cancelActionHandler)
instead of #selector(MockTextFieldTarget.cancelActionHandler)
, you'd get
use of unresolved identifier
error.
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")>
becomes <a id="link">
), and use addEventListener
to bind the event. Put the following in your popup.js
file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js
should be loaded as a separate script file:
<script src="popup.js"></script>
Using select-string:
Get-EventLog Security | where {$_.UserName | select-string -notmatch user1,user2}
For Symfony users: Add a default to your orm column as follows:
/**
* @var DateTime $updatedAt
*
* @ORM\Column(name="updated_at", type="datetime", nullable=false, options={"default" : "CURRENT_TIMESTAMP"})
*/
List images:
ahanjura@ubuntu:~$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED SIZE 88282f8eda00 19 seconds ago 308.5 MB 13e5d3d682f4 19 hours ago 663 MB busybox2 latest 05fe66bb1144 20 hours ago 1.129 MB ubuntu 16.04 00fd29ccc6f1 5 days ago 110.5 MB ubuntu 14.04 67759a80360c 5 days ago 221.4 MB python 2.7 9e92c8430ba0 7 days ago 680.7 MB busybox latest 6ad733544a63 6 weeks ago 1.129 MB ubuntu 16.10 7d3f705d307c 5 months ago 106.7 MB
Delete images:
ahanjura@ubuntu:~$ sudo docker rmi 88282f8eda00
Deleted: sha256:88282f8eda0036f85b5652c44d158308c6f86895ef1345dfa788318e6ba31194 Deleted: sha256:4f211a991fb392cd794bc9ad8833149cd9400c5955958c4017b1e2dc415e25e9 Deleted: sha256:8cc6917ac7f0dcb74969ae7958fe80b4a4ea7b3223fc888dfe1aef42f43df6f8 Deleted: sha256:b74a8932cff5e61c3fd2cc39de3c0989bdfd5c2e5f72b8f99f2807595f8ece43
ahanjura@ubuntu:~$ sudo docker rmi 13e5d3d682f4
Error response from daemon: conflict: unable to delete 13e5d3d682f4 (must be forced) - image is being used by stopped container 5593e25eb638
Delete by force:
ahanjura@ubuntu:~$ sudo docker rmi -f 13e5d3d682f4
Deleted: sha256:13e5d3d682f4de973780b35a3393c46eb314ef3db45d3ae83baf2dd9d702747e Deleted: sha256:3ad9381c7041c03768ccd855ec86caa6bc0244223f10b0465c4898bdb21dc378 Deleted: sha256:5ccb917bce7bc8d3748eccf677d7b60dd101ed3e7fd2aedebd521735276606af Deleted: sha256:18356d19b91f0abcc04496729c9a4c49e695dbfe3f0bb1c595f30a7d4d264ebf
The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile
:
$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
If you need a greater control, that WebClient
does not offer (like TLS/SSL encryption, etc), use FtpWebRequest
. Easy way is to just copy a FileStream
to FTP stream using Stream.CopyTo
:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$fileStream.CopyTo($ftpStream)
$ftpStream.Dispose()
$fileStream.Dispose()
If you need to monitor an upload progress, you have to copy the contents by chunks yourself:
$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()
$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$ftpStream.Write($buffer, 0, $read)
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress `
-Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
-PercentComplete ($pct * 100)
}
$ftpStream.Dispose()
$fileStream.Dispose()
If you want to upload all files from a folder, see
PowerShell Script to upload an entire folder to FTP
I faced the same situation a couple of days ago, and my solution was to define a function in the module to test and just mock that:
def get_date_now():
return datetime.datetime.now()
Today I found out about FreezeGun, and it seems to cover this case beautifully
from freezegun import freeze_time
import datetime
import unittest
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
If you need just any one row from the right side
SELECT SuspReason, SiteID FROM(
SELECT SUSP.Susp_Visits.SuspReason, SUSP.Susp_Visits.SiteID, ROW_NUMBER()
OVER(PARTITION BY SUSP.Susp_Visits.SiteID) AS rn
FROM SUSP.Susp_Visits
LEFT OUTER JOIN DATA.Dim_Member ON SUSP.Susp_Visits.MemID = DATA.Dim_Member.MembershipNum
) AS t
WHERE rn=1
or just
SELECT SUSP.Susp_Visits.SuspReason, SUSP.Susp_Visits.SiteID
FROM SUSP.Susp_Visits WHERE EXISTS(
SELECT DATA.Dim_Member WHERE SUSP.Susp_Visits.MemID = DATA.Dim_Member.MembershipNum
)
Better late than never i suppose... you get the option to set the MASTERPAGE only of you are developing a WEB SITE (FILE>NEW>WEBSITE)... but not when you create an ASP.NET project (FILE>NEW>PROJECT) - there you have to set the Masterpage using the properties of the newly created webform and it's up to you to modify the ASPX source to make it master page compliant (ie, removing the stock HTML, etc...)
I have had this same problem with the x64 version installation. It relates (in my case at least) to the dexplore.exe installation. I uninstalled dexplore, reinstalled it, did a heap of registry changes, etc. as per various blogs and SDKs all to no avail. What finally fixed it for me was editing this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer\DisableBrowse
I changed the value to 0. Once the SDK had installed (quite happily this time) I set the value back to 1.
What alerted me to the possible error was the following in the SDK setup log:
12:19:42 PM Friday, 8 January 2010: SFX C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation started with log file C:\TEMP\Microsoft Windows SDK for Windows 7_dd2d9383-116d-441f-85b3-7c16aeb3568e_SFX.log
12:19:47 PM Friday, 8 January 2010: C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation failed with return code 1625
And this in the dexplore installation logfile:
MSI (s) (E4:7C) [12:19:46:680]: Machine policy value 'DisableBrowse' is 1
MSI (s) (E4:7C) [12:19:46:680]: Adding new sources is not allowed.
MSI (s) (E4:7C) [12:19:46:680]: Warning: rejected attempt to add new source 'c:\eb66d60e4283bfc2986755fa\' (product: {6753B40C-0FBD-3BED-8A9D-0ACAC2DCD85D})
MSI (s) (E4:7C) [12:19:46:680]: MSI_LUA: Elevation prompt disabled for silent installs
MSI (s) (E4:7C) [12:19:46:680]: Note: 1: 1729
MSI (s) (E4:7C) [12:19:46:680]: Product: Microsoft Document Explorer 2008 -- Configuration failed.
I hope this is of assistance in your situation.
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.
When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?
In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.
So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.
And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.
GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.
One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.
git diff > git-dif-file.diff
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
you must use the following properties for a button
element to make it transparent.
button {
background: transparent;
border: none !important;
font-size:0;
}
button {
background: transparent;
border: none !important;
}?
and use absolute position
to position the element.
you have the button element under a div. Use position
: relative on div and position
: absolute on the button to position it within the div.
here is a working JSFiddle
here is an updated JSFiddle that displays only text from the button.
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}
To assign value to a single Form control/individually, I propose to use setValue in the following way:
this.editqueForm.get('user').setValue(this.question.user);
this.editqueForm.get('questioning').setValue(this.question.questioning);
This is actually a multi-step process. First you'll need to add all your files to the current stage:
git add .
You can verify that your files will be added when you commit by checking the status of the current stage:
git status
The console should display a message that lists all of the files that are currently staged, like this:
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: README
# new file: src/somefile.js
#
If it all looks good then you're ready to commit. Note that the commit action only commits to your local repository.
git commit -m "some message goes here"
If you haven't connected your local repository to a remote one yet, you'll have to do that now. Assuming your remote repository is hosted on GitHub and named "Some-Awesome-Project", your command is going to look something like this:
git remote add origin [email protected]:username/Some-Awesome-Project
It's a bit confusing, but by convention we refer to the remote repository as 'origin' and the initial local repository as 'master'. When you're ready to push your commits to the remote repository (origin), you'll need to use the 'push' command:
git push origin master
For more information check out the tutorial on GitHub: http://learn.github.com/p/intro.html
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 OverviewIn ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } ...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------ export default function () { ··· } // no semicolon!
Based on the above we need the export
, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it with these thre ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
I would really strongly suggest to check this Q & A:
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module
inside of test.ts
. This could be the content of it adjusted test.ts
:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The
export =
syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
Try
cordova platform version
It will give you the following output
Installed platforms: android 3.5.1, ios 3.5.0
Available platforms: amazon-fireos, blackberry10, browser, firefoxos
Also to know the version of cordodva cli try
cordova -v
Following this question, in Angular 7.2 you can pass data from parent to child using the history state. So you can do something like
Send:
this.router.navigate(['action-selection'], { state: { example: 'bar' } });
Retrieve:
constructor(private router: Router) { console.log(this.router.getCurrentNavigation().extras.state.example); }
But be careful to be consistent. For example, suppose you want to display a list on a left side bar and the details of the selected item on the right by using a router-outlet. Something like:
Item 1 (x) | ..............................................
Item 2 (x) | ......Selected Item Details.......
Item 3 (x) | ..............................................
Item 4 (x) | ..............................................
Now, suppose you have already clicked some items. Clicking the browsers back buttons will show the details from the previous item. But what if, meanwhile, you have clicked the (x) and delete from your list that item? Then performing the back click, will show you the details of a deleted item.
For recovering a deleted branch, First go through the reflog history,
git reflog -n 60
Where n refers to the last n commits. Then find the proper head and create a branch with that head.
git branch testbranch HEAD@{30}
Unfortunately, not really implemented in ES6. You have this feature with OrderedMap.sort() from ImmutableJS or _.sortBy() from Lodash.
One of the errors I found around Maven is when I put my settings.xml file in the wrong directory. It has to be in .m2 folder under your user home dir. Check to make sure that is in the right place (along with settings-security.xml if you are using that).
Check the Sources-> Scripts in browser Inspect tool. Sometimes multiple jQuery files can be referring. In ASP.NET MVC, this usually happens when the layout page already has a jQuery reference.
A slightly different approach worked for me :-
const normalize = (size: number): number => {
const scale = screenWidth / 320;
const newSize = size * scale;
let calculatedSize = Math.round(PixelRatio.roundToNearestPixel(newSize))
if (PixelRatio.get() < 3)
return calculatedSize - 0.5
return calculatedSize
};
Do refer Pixel Ratio as this allows you to better set up the function based on the device density.
you can use Android Asset in android studio , and android Asset will give you image in this size as a drawable and the application will automatically use the size based on screen of device or emulate
You don't have to implement your own FIFO Queue, just look at the interface java.util.Queue and its implementations
if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php
select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
from ...
or
select to_char(date_field,'mon dd, yyyy')
from ...
My two cents:
One of the goals of strict mode is to allow for faster debugging of issues. It helps the developers by throwing exception when certain wrong things occur that can cause silent & strange behaviour of your webpage. The moment we use use strict
, the code will throw out errors which helps developer to fix it in advance.
Few important things which I have learned after using use strict
:
Prevents Global Variable Declaration:
var tree1Data = { name: 'Banana Tree',age: 100,leafCount: 100000};
function Tree(typeOfTree) {
var age;
var leafCount;
age = typeOfTree.age;
leafCount = typeOfTree.leafCount;
nameoftree = typeOfTree.name;
};
var tree1 = new Tree(tree1Data);
console.log(window);
Now,this code creates nameoftree
in global scope which could be accessed using window.nameoftree
. When we implement use strict
the code would throw error.
Uncaught ReferenceError: nameoftree is not defined
Eliminates with
statement :
with
statements can't be minified using tools like uglify-js. They're also deprecated and removed from future JavaScript versions.
Prevents Duplicates :
When we have duplicate property, it throws an exception
Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode
"use strict";
var tree1Data = {
name: 'Banana Tree',
age: 100,
leafCount: 100000,
name:'Banana Tree'
};
There are few more but I need to gain more knowledge on that.
In my case, this error was caused by a db.close();
out of a 'await' section inside of 'async'
MongoClient.connect(url, {poolSize: 10, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000}, function(err, db) {
// Validate the connection to Mongo
assert.equal(null, err);
// Query the SQL table
querySQL()
.then(function (result) {
console.log('Print results SQL');
console.log(result);
if(result.length > 0){
processArray(db, result)
.then(function (result) {
console.log('Res');
console.log(result);
})
.catch(function (err) {
console.log('Err');
console.log(err);
})
} else {
console.log('Nothing to show in MySQL');
}
})
.catch(function (err) {
console.log(err);
});
db.close(); // <--------------------------------THIS LINE
});
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
[Employee(name=John, age=25, salary=3000.0, mobile=9922001),
Employee(name=Ace, age=22, salary=2000.0, mobile=5924001),
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator
= Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
}
result
[Employee(name=Ace, age=22, salary=2000.0, mobile=5924001),
Employee(name=John, age=25, salary=3000.0, mobile=9922001),
Employee(name=Keith, age=35, salary=4000.0, mobile=3924401)]
I had the same issue and the problem was the size of the picture. Whatsapp doesn't support picture with a size greater than 300KB.
So the most important property to display image on Whatsapp is:
<meta property="og:image" content="url_image">
And the size of the image to display must be less than 300KB
You need to do it through an ArrayAdapter
which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).
This is what the Android developer guide says:
A
ListAdapter
that manages aListView
backed by an array of arbitrary objects. By default this class expects that the provided resource id references a singleTextView
. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference aTextView
in the larger layout resource.However the
TextView
is referenced, it will be filled with thetoString()
of each object in the array. You can add lists or arrays of custom objects. Override thetoString()
method of your objects to determine what text will be displayed for the item in the list.To use something other than
TextViews
for the array display, for instanceImageViews
, or to have some of data besidestoString()
results fill the views, overridegetView(int, View, ViewGroup)
to return the type of view you want.
So your code should look like:
public class YourActivity extends Activity {
private ListView lv;
public void onCreate(Bundle saveInstanceState) {
setContentView(R.layout.your_layout);
lv = (ListView) findViewById(R.id.your_list_view_id);
// Instanciating an array list (you don't need to do this,
// you already have yours).
List<String> your_array_list = new ArrayList<String>();
your_array_list.add("foo");
your_array_list.add("bar");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);
}
}
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
, @Size
and @Min
are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:
manufacturer
shall never be null
licensePlate
shall never be null and must be between 2 and 14 characters long
seatCount
shall be at least 2.
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
The package react-app-rewired can be used to remove the plugin. This way you do not have to eject.
Follow the steps on the npm package page (install the package and flip the calls in the package.json file) and use a config-overrides.js
file similar to this one:
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
module.exports = function override(config, env) {
config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));
return config;
};
This will remove the ModuleScopePlugin from the used WebPack plugins, but leave the rest as it was and removes the necessity to eject.
setState
return a Promise
In addition to passing a callback
to setState()
method, you can wrap it around an async
function and use the then()
method -- which in some cases might produce a cleaner code:
(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
.then(() => { console.log('state:', this.state) });
And here you can take this one more step ahead and make a reusable setState
function that in my opinion is better than the above version:
const promiseState = async state =>
new Promise(resolve => this.setState(state, resolve));
promiseState({...})
.then(() => promiseState({...})
.then(() => {
... // other code
return promiseState({...});
})
.then(() => {...});
This works fine in React 16.4, but I haven't tested it in earlier versions of React yet.
Also worth mentioning that keeping your callback code in componentDidUpdate
method is a better practice in most -- probably all, cases.
Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the v-bind:checked="booleanValue"
or the shorter way :checked="booleanValue"
, for example:
<input
id="checkbox"
type="checkbox"
:value="checkboxVal"
:checked="booleanValue"
v-on:input="checkboxVal = $event.target.value"
/>
That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
With ES6 external modules this can be achieved like so:
// privately scoped array
let arr = [];
export let ArrayModule = {
add: x => arr.push(x),
print: () => console.log(arr),
}
This prevents the use of internal modules and namespaces which is considered bad practice by TSLint [1] [2], allows private and public scoping and prevents the initialisation of unwanted class objects.
You are returning char, and not char*, which is the pointer to the first character of an array.
If you want to return a new character array instead of doing in-place modification, you can ask for an already allocated pointer (char*) as parameter or an uninitialized pointer. In this last case you must allocate the proper number of characters for new string and remember that in C parameters as passed by value ALWAYS, so you must use char** as parameter in the case of array allocated internally by function. Of course, the caller must free that pointer later.
Your query will work in MYSQL
if you set to disable ONLY_FULL_GROUP_BY
server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY
clause, eg
SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2
Non-Aggregated columns means the column is not pass into aggregated functions like SUM
, MAX
, COUNT
, etc..
Here is way to to unset the hover effect.
.table-hover > tbody > tr.hidden-table:hover > td {
background-color: unset !important;
color: unset !important;
}
Add a property to the form method="post"
.
Like this:
<form name="loginform" method="post">
This works for me:
psql postgresql://myuser:password@myhost/my_db -f myInsertFile.sql
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
You can add below code in /config/mail.php ( tested and worked on laravel 5.1, 5.2, 5.4 )
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
Good news! In KitKat there's now a public API for interacting with these secondary shared storage devices.
The new Context.getExternalFilesDirs()
and Context.getExternalCacheDirs()
methods can return multiple paths, including both primary and secondary devices. You can then iterate over them and check Environment.getStorageState()
and File.getFreeSpace()
to determine the best place to store your files. These methods are also available on ContextCompat
in the support-v4 library.
Also note that if you're only interested in using the directories returned by Context
, you no longer need the READ_
or WRITE_EXTERNAL_STORAGE
permissions. Going forward, you'll always have read/write access to these directories with no additional permissions required.
Apps can also continue working on older devices by end-of-lifing their permission request like this:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
(I have extracted this extension from the jQuery UI framework)
Works with: empty()
and html()
and remove()
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
With this solution you can also unbind the event handler.
$("YourElemSelector").off("remove");
Try it! - Example
$.cleanData = (function(orig) {_x000D_
return function(elems) {_x000D_
var events, elem, i;_x000D_
for (i = 0;_x000D_
(elem = elems[i]) != null; i++) {_x000D_
try {_x000D_
_x000D_
// Only trigger remove when necessary to save time_x000D_
events = $._data(elem, "events");_x000D_
if (events && events.remove) {_x000D_
$(elem).triggerHandler("remove");_x000D_
}_x000D_
_x000D_
// Http://bugs.jquery.com/ticket/8235_x000D_
} catch (e) {}_x000D_
}_x000D_
orig(elems);_x000D_
};_x000D_
})($.cleanData);_x000D_
_x000D_
_x000D_
$("#DivToBeRemoved").on("remove", function() {_x000D_
console.log("div was removed event fired");_x000D_
});_x000D_
_x000D_
$("p").on("remove", function() {_x000D_
console.log("p was removed event fired");_x000D_
});_x000D_
_x000D_
$("span").on("remove", function() {_x000D_
console.log("span was removed event fired");_x000D_
});_x000D_
_x000D_
// $("span").off("remove");_x000D_
_x000D_
$("#DivToBeRemoved").on("click", function() {_x000D_
console.log("Div was clicked");_x000D_
});_x000D_
_x000D_
function RemoveDiv() {_x000D_
// $("#DivToBeRemoved").parent().html(""); _x000D_
$("#DivToBeRemoved").remove();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>_x000D_
<div class="container">_x000D_
<br>_x000D_
<button onclick="RemoveDiv();">Click here to remove div below</button>_x000D_
<div id="DivToBeRemoved">_x000D_
DIV TO BE REMOVED _x000D_
contains 1 p element _x000D_
which in turn contains a span element_x000D_
<p>i am p (within div)_x000D_
<br><br><span>i am span (within div)</span></p>_x000D_
</div>_x000D_
</div>
_x000D_
Additional Demo - jsBin
this should work, had to try a while too.. :D
function showHide(shID) {_x000D_
if (document.getElementById(shID)) {_x000D_
if (document.getElementById(shID + '-show').style.display != 'none') {_x000D_
document.getElementById(shID + '-show').style.display = 'none';_x000D_
document.getElementById(shID + '-hide').style.display = 'inline';_x000D_
document.getElementById(shID).style.height = '100px';_x000D_
} else {_x000D_
document.getElementById(shID + '-show').style.display = 'inline';_x000D_
document.getElementById(shID + '-hide').style.display = 'none';_x000D_
document.getElementById(shID).style.height = '0px';_x000D_
}_x000D_
}_x000D_
}
_x000D_
#example {_x000D_
background: red;_x000D_
height: 0px;_x000D_
overflow: hidden;_x000D_
transition: height 2s;_x000D_
-moz-transition: height 2s;_x000D_
/* Firefox 4 */_x000D_
-webkit-transition: height 2s;_x000D_
/* Safari and Chrome */_x000D_
-o-transition: height 2s;_x000D_
/* Opera */_x000D_
}_x000D_
_x000D_
a.showLink,_x000D_
a.hideLink {_x000D_
text-decoration: none;_x000D_
background: transparent url('down.gif') no-repeat left;_x000D_
}_x000D_
_x000D_
a.hideLink {_x000D_
background: transparent url('up.gif') no-repeat left;_x000D_
}
_x000D_
Here is some text._x000D_
<div class="readmore">_x000D_
<a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;">Read more</a>_x000D_
<div id="example" class="more">_x000D_
<div class="text">_x000D_
Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet._x000D_
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas._x000D_
</div>_x000D_
<p>_x000D_
<a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide</a>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
For those who use NSwag and need a custom header:
app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
{
settings.GeneratorSettings.IsAspNetCore = true;
settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));
settings.GeneratorSettings.DocumentProcessors.Add(
new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme
{
Type = SwaggerSecuritySchemeType.ApiKey,
Name = "header-name",
Description = "header description",
In = SwaggerSecurityApiKeyLocation.Header
}));
});
}
Swagger UI will then include an Authorize button.
Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.
This is going to be in res/menu/main_menu
.
res
folder and choose New > Android Resource File.main_menu
for the File name.Paste in the following content as a starter.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_add"
android:icon="@drawable/ic_add"
app:showAsAction="ifRoom"
android:title="Add">
</item>
<item
android:id="@+id/action_settings"
app:showAsAction="never"
android:title="Settings">
</item>
</menu>
You can right click res
and choose New image asset to create the ic_add
icon.
In your activity add the following method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
Also in your Activity, add the following method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_add:
addSomething();
return true;
case R.id.action_settings:
startSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Although Array.forEach is not asynchronous, you can get asynchronous "end result". Example below:
function delayFunction(x) {
return new Promise(
(resolve) => setTimeout(() => resolve(x), 1000)
);
}
[1, 2, 3].forEach(async(x) => {
console.log(x);
console.log(await delayFunction(x));
});
_x000D_
You can use %%~nf
to get the filename only as described in the reference for for
:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
The following options are available:
Variable with modifier Description %~I Expands %I which removes any surrounding quotation marks (""). %~fI Expands %I to a fully qualified path name. %~dI Expands %I to a drive letter only. %~pI Expands %I to a path only. %~nI Expands %I to a file name only. %~xI Expands %I to a file extension only. %~sI Expands path to contain short names only. %~aI Expands %I to the file attributes of file. %~tI Expands %I to the date and time of file. %~zI Expands %I to the size of file. %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
Use this if you're using fragment or add it in your button click listener. This works for me.
requireActivity().onBackPressed()
Called when the activity has detected the user's press of the back key. The getOnBackPressedDispatcher() OnBackPressedDispatcher} will be given chance to handle the back button before the default behavior of android.app.Activity#onBackPressed()} is invoked.
I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.
Here is a small ETF portfolio example.
library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)
VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))
index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))
Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices,
TLT.prices, TIP.prices)
colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")
returnscc.z = diff(log(Prices.z))
start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z)
head(returnscc.z)
Return Matrix
ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)
Box Plot of Return Matrix
chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
element.color = "darkgray", outlier.symbol = 20,
xlab="Continuously Compounded Returns", sort.ascending=F)
You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)
If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.
The only way I though of to do that was to create a temporary vector3
and pretend to do a set_intersection
by adding all elements of vector1
to it, then doing a search for each individual element of vector2
in vector3
and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.
Really, though, just sort them first.
Setting a height on your body and html of 100% should fix you up. Without a defined height your content is not overflowing, so you will not get the desired behavior.
html, body {
overflow-y:hidden;
height:100%;
}
If you can use C#6 or higher, you can benefit from Interpolated Strings and rewrite @Ari Roth's solution like this:
C# 6 :
public static class ColorConverterExtensions
{
public static string ToHexString(this Color c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}";
public static string ToRgbString(this Color c) => $"RGB({c.R}, {c.G}, {c.B})";
}
Also:
this
to use them as extensions methods.string
instead of the class name.SELECT * INTO [table_a] FROM dbo.myView
Yes, via the text-overflow
property in CSS 3. Caveat: it is not universally supported yet in browsers.
Your trouble is that you have some code that is expecting datetime
to be a reference to the datetime
module and other code that is expecting datetime
to be a reference to the datetime
class. Obviously, it can't be both.
When you do:
from datetime import datetime
import datetime
You are first setting datetime
to be a reference to the class, then immediately setting it to be a reference to the module. When you do it the other way around, it's the same thing, but it ends up being a reference to the class.
You need to rename one of these references. For example:
import datetime as dt
from datetime import datetime
Then you can change references in the form datetime.xxxx
that refer to the module to dt.xxxx
.
Or else just import datetime
and change all references to use the module name. In other words, if something just says datetime(...)
you need to change that reference to datetime.datetime
.
Python has a fair bit of this kind of thing in its library, unfortunately. If they followed their own naming guidelines in PEP 8, the datetime
class would be named Datetime
and there'd be no problem using both datetime
to mean the module and Datetime
to mean the class.
You could just do:
var singleton = new (function() {
var bar = 123
this.foo = function() {
// Whatever
}
})()
For this particular query, why make expensive function calls for each row when you could just ask for values starting at the next higher second:
select *
from table
where date >= '2010-07-20 03:21:53'
Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.
=================================================================================
Its been almost 6 months and I believe I should update this with an alternative solution you might want to consider.
As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.
Permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Code:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
ArrayList<String> googleAccounts = new ArrayList<String>();
for (Account ac : accounts) {
String acname = ac.name;
String actype = ac.type;
// Take your time to look at all available accounts
System.out.println("Accounts : " + acname + ", " + actype);
}
Check actype for whatsapp account
if(actype.equals("com.whatsapp")){
String phoneNumber = ac.name;
}
Of course you may not get it if user did not install Whatsapp, but its worth to try anyway. And remember you should always ask user for confirmation.
CMAKE_<LANG>_COMPILER
path without triggering a reconfigureI wanted to compile with an alternate compiler, but also pass -D options on the command-line which would get wiped out by setting a different compiler. This happens because it triggers a re-configure. The trick is to disable the compiler detection with NONE
, set the paths with FORCE
, then enable_language
.
project( sample_project NONE )
set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" FORCE )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" FORCE )
enable_language( C CXX )
The more sensible choice is to create a toolchain file.
set( CMAKE_SYSTEM_NAME Darwin )
set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" )
Then you invoke Cmake with an additional flag
cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/toolchain_file.cmake ...
Add this to pom.xml
(inside the project
tag)
<build>
<sourceDirectory>src/main/java</sourceDirectory>
</build>
src/main/java
is the source folder you want to set. If you already have this line in your pom.xml
file, check if it's correct.
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!
Lazy loaded objects are subclasses
If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass()
will return false
. For example:
Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy
If you're dealing with an ORM, using o instanceof Person
is the only thing that will behave correctly.
Lazy loaded objects have null-fields
ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name
will be null
if person
is lazy loaded, even if person.getName()
forces loading and returns "John Doe". In my experience, this crops up more often in hashCode()
and equals()
.
If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode()
and equals()
.
Saving an object will change its state
Persistent objects often use a id
field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode()
. But you can use it in equals()
.
A pattern I often use is
if (this.getId() == null) {
return this == other;
}
else {
return this.getId().equals(other.getId());
}
But: you cannot include getId()
in hashCode()
. If you do, when an object is persisted, its hashCode
changes. If the object is in a HashSet
, you'll "never" find it again.
In my Person
example, I probably would use getName()
for hashCode
and getId()
plus getName()
(just for paranoia) for equals()
. It's okay if there are some risk of "collisions" for hashCode()
, but never okay for equals()
.
hashCode()
should use the non-changing subset of properties from equals()
A quick one for modern browsers:
'14 2'.split(' ').map(Number);
// [14, 2]`
In POSIX systems, you don't find -r
parameter for grep
and your grep -rn "stuff" .
won't run, but if you use find
command it will:
find . -type f -exec grep -n "stuff" {} \; -print
Agreed by Solaris
and HP-UX
.
A short example what is the difference between @Scope("singleton")
(default) and @Scope("prototype")
:
DAO class:
package com.example.demo;
public class Manager {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Configuration:
@Configuration
public class AppConfiguration {
@Bean
@Scope("singleton")
public Manager getManager(){
return new Manager();
}
}
and MainApp:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.example.demo");
context.refresh();
Manager firstManager = context.getBean(Manager.class);
firstManager.setName("Karol");
Manager secondManager = context.getBean(Manager.class);
System.out.println(secondManager.getName());
}
}
In this example the result is: Karol
even if we set this name only for firstManager
object. It's because Spring IoC container created one instance of object. However when we change scope to @Scope("prototype")
in Configuration class then result is: null
because Spring IoC container creates a new bean instance of the object when request for that bean is made.
I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.
Here is the code :
div:has(>input[disabled=disabled]) {
display: none;
}
Maybe it could help some of you.
If anyone is looking for how to do this in React. For a linechart, assuming you have a wrapper component around the chart:
(This assumes you are using v2. You do not need to use react-chartjs
. This is using the normal chart.js
package from npm.)
propTypes: {
data: React.PropTypes.shape({
datasets: React.PropTypes.arrayOf(
React.PropTypes.shape({
})
),
labels: React.PropTypes.array.isRequired
}).isRequired
},
componentDidMount () {
let chartCanvas = this.refs.chart;
let myChart = new Chart(chartCanvas, {
type: 'line',
data: this.props.data,
options: {
...
}
});
this.setState({chart: myChart});
},
componentDidUpdate () {
let chart = this.state.chart;
let data = this.props.data;
data.datasets.forEach((dataset, i) => chart.data.datasets[i].data = dataset.data);
chart.data.labels = data.labels;
chart.update();
},
render () {
return (
<canvas ref={'chart'} height={'400'} width={'600'}></canvas>
);
}
The componentDidUpdate
functionality allows you to update, add, or remove any data from the this.props.data
.
Swift 4
if let window = UIApplication.shared.windows.first {
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
}
Use from class
class fitToTopInsetConstraint: NSLayoutConstraint {
override func awakeFromNib() {
if let window = UIApplication.shared.windows.first {
let topPadding = window.safeAreaInsets.top
self.constant += topPadding
}
}
}
class fitToBottomInsetConstraint: NSLayoutConstraint {
override func awakeFromNib() {
if let window = UIApplication.shared.windows.first {
let bottomPadding = window.safeAreaInsets.bottom
self.constant += bottomPadding
}
}
}
You will see safe area padding when you build your application.
In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
If you still want a custom filter you can pass in the search model to the filter:
<article data-ng-repeat="result in results | cartypefilter:search" class="result">
Where definition for the cartypefilter can look like this:
app.filter('cartypefilter', function() {
return function(items, search) {
if (!search) {
return items;
}
var carType = search.carType;
if (!carType || '' === carType) {
return items;
}
return items.filter(function(element, index, array) {
return element.carType.name === search.carType;
});
};
});
You're looking for the onblur
event. Look here, for more details.
If you are using Visual Studio 2017 or later which ships with MSBuild 15 or later, and your .csproj files are in the new PackageReference
format, the simplest method is to use the new MSBuild Restore
target.
No-one has actually answered the original question, which is "how do I get NuGet packages to auto-restore when building from the command-line with MSBuild?" The answer is: unless you are using the "Enable NuGet package restore" option (which is now deprecated as per this reference), you can't (but see below). If you are trying to do e.g. automated builds on a CI server, this sucks.
However there is a slightly roundabout way to get the desired behaviour:
nuget restore
which will auto-download all the missing packages.msbuild
to build your solution.Aside: while the new and recommended way to do auto package restore involves less clutter in your version control, it also makes command-line package restore impossible unless you jump through the extra hoop of downloading and running nuget.exe
. Progress?
if you use null values in your stored procedure, you will need to set the parameters to accept null values. That worked for me.
follow these steps:
open terminal go to your root dictionary by typing
cd /
you will see Library folder
Now follow this path Library/Java/JVM/bin
Once you get into bin
you can see the javac
file
Now you need to get the path of this folder for that just write this command
pwd
get the path for your javac
.
In .htaccess add this line:
AddCharset utf-8 .html .css .php .txt .js
This is for those that do not have access to their server's conf file. It is just one more thing to try when other attempts failed.
As far as performance issues regarding the use of .htaccess I have not seen this. My typical page load times are 150-200 mS with or without .htaccess
What good is performance if your page does not render correctly. Most shared servers do not allow user access to the config file which is the preferred place to add a character set.
You could improve on the answer from Ponmudi VN:
See this fiddle: https://jsfiddle.net/solarbaypilot/sn3wtea2/
function _isContains(json, keyname, value) {
return Object.keys(json).some(key => {
return typeof json[key] === 'object' ?
_isContains(json[key], keyname, value) : key === keyname && json[key] === value;
});
}
var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};
document.getElementById('dog').innerHTML = _isContains(JSONObject, "name", "dog");
document.getElementById('puppy').innerHTML = _isContains(JSONObject, "name", "puppy");
Try Demo Here
var list ={}; var count= Object.keys(list).length;
To create within a function (for repeat usage) and dynamical limited length, use:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
double[][]
are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = new int [3]; // Create inner array
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
double[,]
are called rectangular arrays
, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:
int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix [i, j] = i * 3 + j;
Culprit: False Data Dependency (and the compiler isn't even aware of it)
On Sandy/Ivy Bridge and Haswell processors, the instruction:
popcnt src, dest
appears to have a false dependency on the destination register dest
. Even though the instruction only writes to it, the instruction will wait until dest
is ready before executing. This false dependency is (now) documented by Intel as erratum HSD146 (Haswell) and SKL029 (Skylake)
Skylake fixed this for lzcnt
and tzcnt
.
Cannon Lake (and Ice Lake) fixed this for popcnt
.
bsf
/bsr
have a true output dependency: output unmodified for input=0. (But no way to take advantage of that with intrinsics - only AMD documents it and compilers don't expose it.)
(Yes, these instructions all run on the same execution unit).
This dependency doesn't just hold up the 4 popcnt
s from a single loop iteration. It can carry across loop iterations making it impossible for the processor to parallelize different loop iterations.
The unsigned
vs. uint64_t
and other tweaks don't directly affect the problem. But they influence the register allocator which assigns the registers to the variables.
In your case, the speeds are a direct result of what is stuck to the (false) dependency chain depending on what the register allocator decided to do.
popcnt
-add
-popcnt
-popcnt
→ next iterationpopcnt
-add
-popcnt
-add
→ next iterationpopcnt
-popcnt
→ next iterationpopcnt
-popcnt
→ next iterationThe difference between 20 GB/s and 26 GB/s seems to be a minor artifact of the indirect addressing. Either way, the processor starts to hit other bottlenecks once you reach this speed.
To test this, I used inline assembly to bypass the compiler and get exactly the assembly I want. I also split up the count
variable to break all other dependencies that might mess with the benchmarks.
Here are the results:
Sandy Bridge Xeon @ 3.5 GHz: (full test code can be found at the bottom)
g++ popcnt.cpp -std=c++0x -O3 -save-temps -march=native
Different Registers: 18.6195 GB/s
.L4:
movq (%rbx,%rax,8), %r8
movq 8(%rbx,%rax,8), %r9
movq 16(%rbx,%rax,8), %r10
movq 24(%rbx,%rax,8), %r11
addq $4, %rax
popcnt %r8, %r8
add %r8, %rdx
popcnt %r9, %r9
add %r9, %rcx
popcnt %r10, %r10
add %r10, %rdi
popcnt %r11, %r11
add %r11, %rsi
cmpq $131072, %rax
jne .L4
Same Register: 8.49272 GB/s
.L9:
movq (%rbx,%rdx,8), %r9
movq 8(%rbx,%rdx,8), %r10
movq 16(%rbx,%rdx,8), %r11
movq 24(%rbx,%rdx,8), %rbp
addq $4, %rdx
# This time reuse "rax" for all the popcnts.
popcnt %r9, %rax
add %rax, %rcx
popcnt %r10, %rax
add %rax, %rsi
popcnt %r11, %rax
add %rax, %r8
popcnt %rbp, %rax
add %rax, %rdi
cmpq $131072, %rdx
jne .L9
Same Register with broken chain: 17.8869 GB/s
.L14:
movq (%rbx,%rdx,8), %r9
movq 8(%rbx,%rdx,8), %r10
movq 16(%rbx,%rdx,8), %r11
movq 24(%rbx,%rdx,8), %rbp
addq $4, %rdx
# Reuse "rax" for all the popcnts.
xor %rax, %rax # Break the cross-iteration dependency by zeroing "rax".
popcnt %r9, %rax
add %rax, %rcx
popcnt %r10, %rax
add %rax, %rsi
popcnt %r11, %rax
add %rax, %r8
popcnt %rbp, %rax
add %rax, %rdi
cmpq $131072, %rdx
jne .L14
So what went wrong with the compiler?
It seems that neither GCC nor Visual Studio are aware that popcnt
has such a false dependency. Nevertheless, these false dependencies aren't uncommon. It's just a matter of whether the compiler is aware of it.
popcnt
isn't exactly the most used instruction. So it's not really a surprise that a major compiler could miss something like this. There also appears to be no documentation anywhere that mentions this problem. If Intel doesn't disclose it, then nobody outside will know until someone runs into it by chance.
(Update: As of version 4.9.2, GCC is aware of this false-dependency and generates code to compensate it when optimizations are enabled. Major compilers from other vendors, including Clang, MSVC, and even Intel's own ICC are not yet aware of this microarchitectural erratum and will not emit code that compensates for it.)
Why does the CPU have such a false dependency?
We can speculate: it runs on the same execution unit as bsf
/ bsr
which do have an output dependency. (How is POPCNT implemented in hardware?). For those instructions, Intel documents the integer result for input=0 as "undefined" (with ZF=1), but Intel hardware actually gives a stronger guarantee to avoid breaking old software: output unmodified. AMD documents this behaviour.
Presumably it was somehow inconvenient to make some uops for this execution unit dependent on the output but others not.
AMD processors do not appear to have this false dependency.
The full test code is below for reference:
#include <iostream>
#include <chrono>
#include <x86intrin.h>
int main(int argc, char* argv[]) {
using namespace std;
uint64_t size=1<<20;
uint64_t* buffer = new uint64_t[size/8];
char* charbuffer=reinterpret_cast<char*>(buffer);
for (unsigned i=0;i<size;++i) charbuffer[i]=rand()%256;
uint64_t count,duration;
chrono::time_point<chrono::system_clock> startP,endP;
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"popcnt %4, %4 \n\t"
"add %4, %0 \n\t"
"popcnt %5, %5 \n\t"
"add %5, %1 \n\t"
"popcnt %6, %6 \n\t"
"add %6, %2 \n\t"
"popcnt %7, %7 \n\t"
"add %7, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "No Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"popcnt %4, %%rax \n\t"
"add %%rax, %0 \n\t"
"popcnt %5, %%rax \n\t"
"add %%rax, %1 \n\t"
"popcnt %6, %%rax \n\t"
"add %%rax, %2 \n\t"
"popcnt %7, %%rax \n\t"
"add %%rax, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
: "rax"
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "Chain 4 \t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
{
uint64_t c0 = 0;
uint64_t c1 = 0;
uint64_t c2 = 0;
uint64_t c3 = 0;
startP = chrono::system_clock::now();
for( unsigned k = 0; k < 10000; k++){
for (uint64_t i=0;i<size/8;i+=4) {
uint64_t r0 = buffer[i + 0];
uint64_t r1 = buffer[i + 1];
uint64_t r2 = buffer[i + 2];
uint64_t r3 = buffer[i + 3];
__asm__(
"xor %%rax, %%rax \n\t" // <--- Break the chain.
"popcnt %4, %%rax \n\t"
"add %%rax, %0 \n\t"
"popcnt %5, %%rax \n\t"
"add %%rax, %1 \n\t"
"popcnt %6, %%rax \n\t"
"add %%rax, %2 \n\t"
"popcnt %7, %%rax \n\t"
"add %%rax, %3 \n\t"
: "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
: "r" (r0), "r" (r1), "r" (r2), "r" (r3)
: "rax"
);
}
}
count = c0 + c1 + c2 + c3;
endP = chrono::system_clock::now();
duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
cout << "Broken Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
<< (10000.0*size)/(duration) << " GB/s" << endl;
}
free(charbuffer);
}
An equally interesting benchmark can be found here: http://pastebin.com/kbzgL8si
This benchmark varies the number of popcnt
s that are in the (false) dependency chain.
False Chain 0: 41959360000 0.57748 sec 18.1578 GB/s
False Chain 1: 41959360000 0.585398 sec 17.9122 GB/s
False Chain 2: 41959360000 0.645483 sec 16.2448 GB/s
False Chain 3: 41959360000 0.929718 sec 11.2784 GB/s
False Chain 4: 41959360000 1.23572 sec 8.48557 GB/s
You need to have the file /root/test/devenv/openstack-rhel/pom.xml
This file need to have the followings elements:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openstack</groupId>
<artifactId>openstack-rhel-rpms</artifactId>
<version>2012.1-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
I used GENEGC's script, but I found it quite slow.
It is slow because it scans whole sheet on every edit.
So I wrote way faster and cleaner method for myself and I wanted to share it.
function onEdit(e) {
if (e) {
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
// If you want to be specific
// do not work in first row
// do not work in other sheets except "MySheet"
if (r.getRow() != 1 && ss.getName() == "MySheet") {
// E.g. status column is 2nd (B)
status = ss.getRange(r.getRow(), 2).getValue();
// Specify the range with which You want to highlight
// with some reading of API you can easily modify the range selection properties
// (e.g. to automatically select all columns)
rowRange = ss.getRange(r.getRow(),1,1,19);
// This changes font color
if (status == 'YES') {
rowRange.setFontColor("#999999");
} else if (status == 'N/A') {
rowRange.setFontColor("#999999");
// DEFAULT
} else if (status == '') {
rowRange.setFontColor("#000000");
}
}
}
}
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
You can run it for machines in your network by
./manage.py runserver 0.0.0.0:8000
And than you will be able to reach you server from any machine in your network.
Just type on other machine in browser http://192.168.0.1:8000
where 192.168.0.1
is IP of you server... and it ready to go....
or in you case:
A
in command line ./manage.py runserver 0.0.0.0:8000
B
in browser type http://A:8000
I had the same problem on Debian, yarn was the solution for me.
I eventually figured it out. Place:
import warnings
warnings.filterwarnings('ignore')
inside ~/.ipython/profile_default/startup/disable-warnings.py
. I'm leaving this question and answer for the record in case anyone else comes across the same issue.
Quite often it is useful to see a warning once. This can be set by:
warnings.filterwarnings(action='once')
This is the simplest one.
#divid {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
the following provides a solution such that to add a new enum requires only a one-line edit, similar work to adding a single line in an enum {} list.
//------------------------------------------------------------------------------
// enum to string example
#define FOR_EACH_GENDER(tbd) \
tbd(GENDER_MALE) \
tbd(GENDER_FEMALE) \
tbd(GENDER_INTERSEX) \
#define ONE_GENDER_ENUM(name) name,
enum
{
FOR_EACH_GENDER(ONE_GENDER_ENUM)
MAX_GENDER
};
#define ONE_GENDER(name) #name,
static const char *enumGENDER_TO_STRING[] =
{
FOR_EACH_GENDER(ONE_GENDER)
};
// access string name with enumGENDER_TO_STRING[value]
// or, to be safe converting from a untrustworthy caller
static const char *enumGenderToString(unsigned int value)
{
if (value < MAX_GENDER)
{
return enumGENDER_TO_STRING[value];
}
return NULL;
}
static void printAllGenders(void)
{
for (int ii = 0; ii < MAX_GENDER; ii++)
{
printf("%d) gender %s\n", ii, enumGENDER_TO_STRING[ii]);
}
}
//------------------------------------------------------------------------------
// you can assign an arbitrary value and/or information to each enum,
#define FOR_EACH_PERSON(tbd) \
tbd(2, PERSON_FRED, "Fred", "Weasley", GENDER_MALE, 12) \
tbd(4, PERSON_GEORGE, "George", "Weasley", GENDER_MALE, 12) \
tbd(6, PERSON_HARRY, "Harry", "Potter", GENDER_MALE, 10) \
tbd(8, PERSON_HERMIONE, "Hermione", "Granger", GENDER_FEMALE, 10) \
#define ONE_PERSON_ENUM(value, ename, first, last, gender, age) ename = value,
enum
{
FOR_EACH_PERSON(ONE_PERSON_ENUM)
};
typedef struct PersonInfoRec
{
int value;
const char *ename;
const char *first;
const char *last;
int gender;
int age;
} PersonInfo;
#define ONE_PERSON_INFO(value, ename, first, last, gender, age) \
{ ename, #ename, first, last, gender, age },
static const PersonInfo personInfo[] =
{
FOR_EACH_PERSON(ONE_PERSON_INFO)
{ 0, NULL, NULL, NULL, 0, 0 }
};
// note: if the enum values are not sequential, you need another way to lookup
// the information besides personInfo[ENUM_NAME]
static void printAllPersons(void)
{
for (int ii = 0; ; ii++)
{
const PersonInfo *pPI = &personInfo[ii];
if (!pPI->ename)
{
break;
}
printf("%d) enum %-15s %8s %-8s %13s %2d\n",
pPI->value, pPI->ename, pPI->first, pPI->last,
enumGenderToString(pPI->gender), pPI->age);
}
}
One important reason for using constructor initializer list which is not mentioned in answers here is initialization of base class.
As per the order of construction, base class should be constructed before child class. Without constructor initializer list, this is possible if your base class has default constructor which will be called just before entering the constructor of child class.
But, if your base class has only parameterized constructor, then you must use constructor initializer list to ensure that your base class is initialized before child class.
Initialization of Subobjects which only have parameterized constructors
Efficiency
Using constructor initializer list, you initialize your data members to exact state which you need in your code rather than first initializing them to their default state & then changing their state to the one you need in your code.
If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.
Reference data members must be intialized when compiler enters constructor as references can't be just declared & initialized later. This is possible only with constructor initializer list.
You can wrap your table around the div tag like this as it helped me too.
<div class="col-md-3">
<table>
</table>
</div>
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
There doesn't seem to be a standardized default value. I have the feeling the default is 0
, and the timeout event left totally dependent on browser and network settings.
For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).
Reverse array and looping through it:
[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
...
}];
Take a look at http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports. You could do
from .mod1 import stuff
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.
Moreover Execute the command
graphics.off()
May help to someone:
I'm sending data from react
application to golang
server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*")
. Error has fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
If you only need the docker process to go in the background you can use
Ctrl + Z
Be aware that it is not a real detach and it comes with a performance penalty.
(You can return it to foreground with the bg
command).
Another option is to just close your terminal, if you don't need it any longer.
What you want is called an associative array. In python these are called dictionaries.
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.
myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"
Alternative way to create the above dict:
myDict = {"john": "johns value", "jeff": "jeffs value"}
Accessing values:
print(myDict["jeff"]) # => "jeffs value"
Getting the keys (in Python v2):
print(myDict.keys()) # => ["john", "jeff"]
In Python 3, you'll get a dict_keys
, which is a view and a bit more efficient (see views docs and PEP 3106 for details).
print(myDict.keys()) # => dict_keys(['john', 'jeff'])
If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
If you can run the "sdkmanager" from the command line, then running sdkmanager --verbose --list
will reveal the paths it checks.
For example, I have installed the SDK in c:\spool\Android
and for me running the sdkmanager --verbose --list
looks like:
>sdkmanager --list --verbose
Info: Parsing c:\spool\Android\build-tools\27.0.3\package.xml
Info: Parsing c:\spool\Android\emulator\package.xml
Info: Parsing c:\spool\Android\extras\android\m2repository\package.xml
Info: Parsing c:\spool\Android\extras\intel\Hardware_Accelerated_Execution_Manager\package.xml
Info: Parsing c:\spool\Android\patcher\v4\package.xml
Info: Parsing c:\spool\Android\platform-tools\package.xml
Info: Parsing c:\spool\Android\platforms\android-27\package.xml
Info: Parsing c:\spool\Android\tools\package.xml
Installed packages:=====================] 100% Computing updates...
--------------------------------------
build-tools;27.0.3
Description: Android SDK Build-Tools 27.0.3
Version: 27.0.3
Installed Location: c:\spool\Android\build-tools\27.0.3
P.S. On another PC I let the Android Studio install the Android SDK for me, and the SDK ended up in C:\Users\MyUsername\AppData\Local\Android\Sdk
.
Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:
>>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)
This should get you started:
set datafile separator ","
plot 'infile' using 0:1
A bit late but as this is an ongoing issue with Mac OSX...
The simplest solution I found was to simply remove the OpenJDK stuff that Apple installs. Every time an update of Mac OSX arrives it gets installed and you'll need to remove it again.
This works really well if you develop apps for Google App Engine on your mac using Java. The OpenJDK does not work well and the Java version that comes with the Mac OSX Yosemite upgrade will make the Eclipse Plug-in for App Engine crash on every deployment with the helpful error: "Read timed out".
You can try 'onbeforeunload
' event.
Also take a look at this-
Why don't you set both Background & BorderBrush
by same brush
<Style TargetType="{x:Type Button}" >
<Setter Property="Background" Value="{StaticResource marginBackGround}"></Setter>
<Setter Property="BorderBrush" Value="{StaticResource marginBackGround}"></Setter>
</Style>
<LinearGradientBrush x:Key="marginBackGround" EndPoint=".5,1" StartPoint="0.5,0">
<GradientStop Color="#EE82EE" Offset="0"/>
<GradientStop Color="#7B30B6" Offset="0.5"/>
<GradientStop Color="#510088" Offset="0.5"/>
<GradientStop Color="#76209B" Offset="0.9"/>
<GradientStop Color="#C750B9" Offset="1"/>
</LinearGradientBrush>
With Java 9
, we can use ProcessHandle which makes it easier to identify and control native processes:
ProcessHandle
.allProcesses()
.filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
.findFirst()
.ifPresent(ProcessHandle::destroy)
where "firefox" is the process to kill.
This:
First lists all processes running on the system as a Stream<ProcessHandle>
Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both commandLine
or command
can be used depending on how we want to retrieve the process.
Finds the first filtered process meeting the filtering condition.
And if at least one process' command line contained "firefox", then kills it using destroy
.
No import necessary as ProcessHandle
is part of java.lang
.
I had a similar problem, but I only needed the bytes from the file. I read through links provided in the various answers, and ultimately tried writing one similar to #5 in Evgeniy's answer. They weren't kidding, it took a lot of code.
The basic premise is that each line of text is of unknown length. I will start with a SeekableByteChannel, read data into a ByteBuffer, then loop over it looking for EOL. When something is a "carryover" between loops, it increments a counter and then ultimately moves the SeekableByteChannel position around and reads the entire buffer.
It is verbose ... but it works. It was plenty fast for what I needed, but I'm sure there are more improvements that can be made.
The process method is stripped down to the basics for kicking off reading the file.
private long startOffset;
private long endOffset;
private SeekableByteChannel sbc;
private final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
public void process() throws IOException
{
startOffset = 0;
sbc = Files.newByteChannel(FILE, EnumSet.of(READ));
byte[] message = null;
while((message = readRecord()) != null)
{
// do something
}
}
public byte[] readRecord() throws IOException
{
endOffset = startOffset;
boolean eol = false;
boolean carryOver = false;
byte[] record = null;
while(!eol)
{
byte data;
buffer.clear();
final int bytesRead = sbc.read(buffer);
if(bytesRead == -1)
{
return null;
}
buffer.flip();
for(int i = 0; i < bytesRead && !eol; i++)
{
data = buffer.get();
if(data == '\r' || data == '\n')
{
eol = true;
endOffset += i;
if(carryOver)
{
final int messageSize = (int)(endOffset - startOffset);
sbc.position(startOffset);
final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(messageSize);
sbc.read(tempBuffer);
tempBuffer.flip();
record = new byte[messageSize];
tempBuffer.get(record);
}
else
{
record = new byte[i];
// Need to move the buffer position back since the get moved it forward
buffer.position(0);
buffer.get(record, 0, i);
}
// Skip past the newline characters
if(isWindowsOS())
{
startOffset = (endOffset + 2);
}
else
{
startOffset = (endOffset + 1);
}
// Move the file position back
sbc.position(startOffset);
}
}
if(!eol && sbc.position() == sbc.size())
{
// We have hit the end of the file, just take all the bytes
record = new byte[bytesRead];
eol = true;
buffer.position(0);
buffer.get(record, 0, bytesRead);
}
else if(!eol)
{
// The EOL marker wasn't found, continue the loop
carryOver = true;
endOffset += bytesRead;
}
}
// System.out.println(new String(record));
return record;
}
In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?
Session.Abandon() destroys the session and the Session_OnEnd event is triggered.
Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.
What is the difference between Session.Abandon() and Session.Clear()
Clear - Removes all keys and values from the session-state collection.
Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out. It also raises events like Session_End.
Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.
...
Generally, in most cases you need to use Session.Clear. You can use Session.Abandon if you are sure the user is going to leave your site.
So back to the differences:
- Abandon raises Session_End request.
- Clear removes items immediately, Abandon does not.
- Abandon releases the SessionState object and its items so it can garbage collected.
- Clear keeps SessionState and resources associated with it.
Session.Clear() or Session.Abandon() ?
You use Session.Clear() when you don't want to end the session but rather just clear all the keys in the session and reinitialize the session.
Session.Clear() will not cause the Session_End eventhandler in your Global.asax file to execute.
But on the other hand Session.Abandon() will remove the session altogether and will execute Session_End eventhandler.
Session.Clear() is like removing books from the bookshelf
Session.Abandon() is like throwing the bookshelf itself.
Question
I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?
Answer
If you want the user to login again, use Session.Abandon.
Gradle nicely combines both Ant and Maven, taking the best from both frameworks. Flexibility from Ant and convention over configuration, dependency management and plugins from Maven.
So if you want to have a standard java build, like in maven, but test task has to do some custom step it could look like below.
build.gradle:
apply plugin:'java'
task test{
doFirst{
ant.copy(toDir:'build/test-classes'){fileset dir:'src/test/extra-resources'}
}
doLast{
...
}
}
On top of that it uses groovy syntax which gives much more expression power then ant/maven's xml.
It is a superset of Ant - you can use all Ant tasks in gradle with nicer, groovy-like syntax, ie.
ant.copy(file:'a.txt', toDir:"xyz")
or
ant.with{
delete "x.txt"
mkdir "abc"
copy file:"a.txt", toDir: "abc"
}
Here's an improved looping method that uses binary search to find the largest possible size that fits into the parent in the fewest steps possible (this is faster and more accurate than stepping by a fixed font size). The code is also optimized in several ways for performance.
By default, 10 binary search steps will be performed, which will get within 0.1% of the optimal size. You could instead set numIter to some value N to get within 1/2^N of the optimal size.
Call it with a CSS selector, e.g.: fitToParent('.title-span');
/**
* Fit all elements matching a given CSS selector to their parent elements'
* width and height, by adjusting the font-size attribute to be as large as
* possible. Uses binary search.
*/
var fitToParent = function(selector) {
var numIter = 10; // Number of binary search iterations
var regexp = /\d+(\.\d+)?/;
var fontSize = function(elem) {
var match = elem.css('font-size').match(regexp);
var size = match == null ? 16 : parseFloat(match[0]);
return isNaN(size) ? 16 : size;
}
$(selector).each(function() {
var elem = $(this);
var parentWidth = elem.parent().width();
var parentHeight = elem.parent().height();
if (elem.width() > parentWidth || elem.height() > parentHeight) {
var maxSize = fontSize(elem), minSize = 0.1;
for (var i = 0; i < numIter; i++) {
var currSize = (minSize + maxSize) / 2;
elem.css('font-size', currSize);
if (elem.width() > parentWidth || elem.height() > parentHeight) {
maxSize = currSize;
} else {
minSize = currSize;
}
}
elem.css('font-size', minSize);
}
});
};
#testDiv{
/* set green border independently on each side */
border-left: solid green 2px;
border-right: solid green 2px;
border-bottom: solid green 2px;
border-top: solid green 2px;
}
Use boolean
indexing as you would do in numpy.array
df = pd.DataFrame({'Data':np.random.normal(size=200)})
# example dataset of normally distributed data.
df[np.abs(df.Data-df.Data.mean()) <= (3*df.Data.std())]
# keep only the ones that are within +3 to -3 standard deviations in the column 'Data'.
df[~(np.abs(df.Data-df.Data.mean()) > (3*df.Data.std()))]
# or if you prefer the other way around
For a series it is similar:
S = pd.Series(np.random.normal(size=200))
S[~((S-S.mean()).abs() > 3*S.std())]
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
If you set Vim to use the system clipboard (:set clipboard=unnamed
), then any text you copy in Vim can be pasted using Shift + Insert. Shift + Insert is simply an OS-wide paste key-combination (Ctrl + Insert is the corresponding 'copy').
You can try the following library: Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.
If you love the command line, you can also do this using drush with the watchdog show command:
drush ws
More information about this command available here:
From this question: https://dba.stackexchange.com/questions/114958/list-all-tables-from-all-user-databases/230411#230411
I added record count to the answer provided by @Aaron Bertrand that lists all databases and all tables.
DECLARE @src NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @sql = N'', @src = N' UNION ALL
SELECT ''$d'' as ''database'',
s.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''schema'',
t.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''table'' ,
ind.rows as record_count
FROM [$d].sys.schemas AS s
INNER JOIN [$d].sys.tables AS t ON s.[schema_id] = t.[schema_id]
INNER JOIN [$d].sys.sysindexes AS ind ON t.[object_id] = ind.[id]
where ind.indid < 2';
SELECT @sql = @sql + REPLACE(@src, '$d', name)
FROM sys.databases
WHERE database_id > 4
AND [state] = 0
AND HAS_DBACCESS(name) = 1;
SET @sql = STUFF(@sql, 1, 10, CHAR(13) + CHAR(10));
PRINT @sql;
--EXEC sys.sp_executesql @sql;
As the error states - the database is not open - it was previously shut down, and someone left it in the middle of the startup process. They may either be intentional, or unintentional (i.e., it was supposed to be open, but failed to do so).
Assuming that's nothing wrong with the database itself, you could open it with a simple statement. (Since the question is asked specifically in the context of SQLPlus, kindly remember to put a statement terminator(Semicolon) at the end mandatorily, otherwise, it will result in an error. The semicolon character is a statement terminator. It is a part of the ANSI SQL-92 standard.)
ALTER DATABASE OPEN;
new Date(timestamp.toDate()).toUTCString()
try this
Calendar c = Calendar.getInstance();
int mseconds = c.get(Calendar.MILLISECOND)
an alternative would be
Calendar rightNow = Calendar.getInstance();
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMid = (rightNow.getTimeInMils() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMid + " milliseconds since midnight");
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
I accidentally installed 'serial' (sudo python -m pip install serial
) instead of 'pySerial' (sudo python -m pip install pyserial
), which lead to the same error.
If the previously mentioned solutions did not work for you, double check if you installed the correct library.
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
Max length will not work with <input type="number"
the best way i know is to use oninput
event to limit the maxlength. Please see the below code for simple implementation.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
In addition to the good answers above to set the navigation view controller on top of your screen on your app, you can add it to your AppDelegate.swift file inside the block as follows
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: LoginViewController())
return true
}
You could use the extension method syntax:
var item = Items.Select(x => x.Id == 123).FirstOrDefault();
Other than that, I'm not sure how much more concise you can get, without maybe writing your own specialized "First" and "FirstOrDefault" extension methods.
I know this is old, but none of these expressions worked for me (maybe it's because I'm on PHP). The following expression worked fine to validate that a number is higher than 49:
/([5-9][0-9])|([1-9]\d{3}\d*)/
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:
XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);
Get Unique Key using GUID Hash code
public static string GetUniqueKey(int length)
{
string guidResult = string.Empty;
while (guidResult.Length < length)
{
// Get the GUID.
guidResult += Guid.NewGuid().ToString().GetHashCode().ToString("x");
}
// Make sure length is valid.
if (length <= 0 || length > guidResult.Length)
throw new ArgumentException("Length must be between 1 and " + guidResult.Length);
// Return the first length bytes.
return guidResult.Substring(0, length);
}
Dim iIndex as Integer
Dim ws As Excel.Worksheet
Dim wb As Workbook
Dim strPath As String
Dim strFile As String
strPath = "D:\Personal\"
strFile = Dir(strPath & "*.xlsx")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strPath & strFile)
For iIndex = 1 To wb.Worksheets.count
Set ws = wb.Worksheets(iIndex)
'Do something here.
Next iIndex
strFile = Dir 'This moves the value of strFile to the next file.
Loop
Many programming languages, especially those derived from C, have support for the so-called Switch Fallthrough. I was searching for the best way to do the same in Ruby and thought it might be useful to others:
In C-like languages fallthrough typically looks like this:
switch (expression) {
case 'a':
case 'b':
case 'c':
// Do something for a, b or c
break;
case 'd':
case 'e':
// Do something else for d or e
break;
}
In Ruby, the same can be achieved in the following way:
case expression
when 'a', 'b', 'c'
# Do something for a, b or c
when 'd', 'e'
# Do something else for d or e
end
This is not strictly equivalent, because it's not possible to let 'a'
execute a block of code before falling through to 'b'
or 'c'
, but for the most part I find it similar enough to be useful in the same way.
You can also split a string at every n-th character and put them each, in each index of a List :
Here I made a list of Strings named Sequence :
List < String > Sequence
Then I'm basically splitting the String "KILOSO" by every 2 words. So 'KI' 'LO' 'SO' would be incorporate in separate index of the List called Sequence.
String S = KILOSO
Sequence = Arrays.asList(S.split("(?<=\G..)"));
So when I'm doing :
System.out.print(Sequence)
It should print :
[KI, LO, SO]
to verify I can write :
System.out.print(Sequence.get(1))
it will print :
LO
At the Android 28(Android P)
startActivity
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
&& (targetSdkVersion < Build.VERSION_CODES.N
|| targetSdkVersion >= Build.VERSION_CODES.P)
&& (options == null
|| ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
throw new AndroidRuntimeException(
"Calling startActivity() from outside of an Activity "
+ " context requires the FLAG_ACTIVITY_NEW_TASK flag."
+ " Is this really what you want?");
}
So the best way is add FLAG_ACTIVITY_NEW_TASK
Intent intent = new Intent(context, XXXActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
The other answers are all correct, but surprisingly all leaving out the theoretical aspect here: return types can be different, but they can only restrict the type used in the super class because of the Liskov Substitution Principle.
It is super simple: when you have "client" code that calls some method:
int foo = someBar.bar();
then the above has to work (and return something that is an int
no matter which implementation of bar()
is invoked).
Meaning: if there is a Bar subclass that overrides bar()
then you still have to return something that doesn't break "caller code".
In other words: assume that the base bar()
is supposed to return int. Then a subclass could return short
- but not long
because callers will be fine dealing with a short
value, but not a long
!
Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.
For example, go to the combo box (CTRL+/) and type: >of MyClassName
. As you type, intellisense will refine the options in the dropdown.
In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:
Using the Go To Find Combo Box
This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
Posting, since it might be useful for someone in the future:
For me, when I got here, the solution was browser cache. Had to hard refresh Chrome (cmd/ctrl+shift+R) to get the new styles applied, it seems the old ones got cached really "deep".
This question/answer might come in handy for someone. And hard refresh tips for different browsers for those who don't use Chrome.
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "POST",
url: urlToSend,
data: { id: clickedButton.val(), access_token: $("#access_token").val() },
success:function(result){
alert('ok');
},
error:function(result)
{
alert('error');
}
});
}
$(document).ready(function(){
$("#button_1").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
$("#button_2").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
});
I wasn't happy with any of the awk
solutions presented here because I wanted to extract the first few columns and then print the rest, so I turned to perl
instead. The following code extracts the first two columns, and displays the rest as is:
echo -e "a b c d\te\t\tf g" | \
perl -ne 'my @f = split /\s+/, $_, 3; printf "first: %s second: %s rest: %s", @f;'
The advantage compared to the perl
solution from Chris Koknat is that really only the first n elements are split off from the input string; the rest of the string isn't split at all and therefor stays completely intact. My example demonstrates this with a mix of spaces and tabs.
To change the amount of columns that should be extracted, replace the 3
in the example with n+1.
This is an old post but regardless, you can also get boldface and italic characters by leveraging utf-32. There are even greek and math symbols that can be used as well as the roman alphabet.
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
I used this and works for me.
<div class="col-sm-3">
<img src="xxx.png" style="width: auto; height: 195px;">
</div>
running your code hundred times may affect the camera to function wrongly.Your activity may be performing correctly but system could not buy it.so camera forces stop. One main tip all missed is rebooting your phone and not only eclipse..It worked for me..
Warning, bug in Android 3 (Honeycomb) and Android 4.0 (Ice Cream Sandwich)
Androids versions: 3.1 - 4.04 have a bug, that setTextSize() inside of TextView works only for the first time (first invocation).
The bug is described in Issue 22493: TextView height bug in Android 4.0 and Issue 17343: button's height and text does not return to its original state after increase and decrease the text size on HoneyComb.
The workaround is to add a newline character to text assigned to TextView before changing size:
final String DOUBLE_BYTE_SPACE = "\u3000";
textView.append(DOUBLE_BYTE_SPACE);
I use it in my code as follow:
final String DOUBLE_BYTE_SPACE = "\u3000";
AutoResizeTextView textView = (AutoResizeTextView) view.findViewById(R.id.aTextView);
String fixString = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1
&& android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
fixString = DOUBLE_BYTE_SPACE;
}
textView.setText(fixString + "The text" + fixString);
I add this "\u3000" character on left and right of my text, to keep it centered. If you have it aligned to left then append to the right only. Of course it can be also embedded with AutoResizeTextView widget, but I wanted to keep fix code outside.
Class methods provide a "semantic sugar" (don't know if this term is widely used) - or "semantic convenience".
Example: you got a set of classes representing objects. You might want to have the class method all()
or find()
to write User.all()
or User.find(firstname='Guido')
. That could be done using module level functions of course...
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
onDestroy
isn't always called in the service so this is useless!
For example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9.
Let's say those radio buttons are inside a div
that has the id radioButtons
and that the radio buttons have the same name (for example commonName
) then:
$('#radioButtons').on('change', 'input[name=commonName]:radio', function (e) {
console.log('You have changed the selected radio button!');
});