How to pass optional arguments to a method in C++?
Here is an example of passing mode as optional parameter
void myfunc(int blah, int mode = 0)
{
if (mode == 0)
do_something();
else
do_something_else();
}
you can call myfunc in both ways and both are valid
myfunc(10); // Mode will be set to default 0
myfunc(10, 1); // Mode will be set to 1
How to Install gcc 5.3 with yum on CentOS 7.2?
Update: Installing latest version of gcc 9: (gcc 9.3.0) - released March 12, 2020:
Same method can be applied to gcc 10 (gcc 10.1.0) - released May 7, 2020
Download file: gcc-9.3.0.tar.gz or
gcc-10.1.0.tar.gz
Compile and install:
//required libraries: (some may already have been installed)
dnf install libmpc-devel mpfr-devel gmp-devel
//if dnf install libmpc-devel is not working try:
dnf --enablerepo=PowerTools install libmpc-devel
//install zlib
dnf install zlib-devel*
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around an hour or more to finish
(depending on your cpu speed)
make install
Tested under CentOS 7.8.2003 for gcc 9.3 and gcc 10.1
Tested under CentOS 8.1.1911 for gcc 10.1 (may take more time to compile)
Results: gcc/g++ 9.3.0/10.1.0
Installing gcc 7.4 (gcc 7.4.0) - released December 6, 2018:
Download file: https://ftp.gnu.org/gnu/gcc/gcc-7.4.0/gcc-7.4.0.tar.gz
Compile and install:
//required libraries:
yum install libmpc-devel mpfr-devel gmp-devel
./configure --with-system-zlib --disable-multilib --enable-languages=c,c++
make -j 8 <== this may take around 50 minutes or less to finish with 8 threads
(depending on your cpu speed)
make install
Result:
Notes:
1. This Stack Overflow answer will help to see how to verify the downloaded source file.
2. Use the option --prefix
to install gcc to another directory other than the default one. The toplevel installation directory defaults to /usr/local. Read about gcc installation options
jQuery see if any or no checkboxes are selected
JQuery .is
will test all specified elements and return true if at least one of them matches selector:
if ($(":checkbox[name='choices']", form).is(":checked"))
{
// one or more checked
}
else
{
// nothing checked
}
Maven in Eclipse: step by step installation
First install maven in your system and set Maven environment variables
- M2_HOME: ....\apache-maven-3.0.5 \ maven installed path
- M2_Repo: D:\maven_repo \If change maven repo location
- M2: %M2_HOME%\bin
Steps to Configures maven on Eclipse IDE:
- Select Window -> Preferences
Note: If Maven option is not present, then add maven 3 to eclipse or install it.
- Add the Maven location of your system
To check maven is configured properly:
Open Eclipse and click on Windows -> Preferences
Choose Maven from left panel, and select installations.
Click on Maven -> "User Settings" option form left panel, to check local repository location.
What is the difference between function and procedure in PL/SQL?
A function can be in-lined into a SQL statement, e.g.
select foo
,fn_bar (foo)
from foobar
Which cannot be done with a stored procedure. The architecture of the query optimiser limits what can be done with functions in this context, requiring that they are pure (i.e. the same inputs always produce the same output). This restricts what can be done in the function, but allows it to be used in-line in the query if it is defined to be "pure".
Otherwise, a function (not necessarily deterministic) can return a variable or a result set. In the case of a function returning a result set, you can join it against some other selection in a query. However, you cannot use a non-deterministic function like this in a correlated subquery as the optimiser cannot predict what sort of result set will be returned (this is computationally intractable, like the halting problem).
Encoding conversion in java
I would just like to add that if the String is originally encoded using the wrong encoding it might be impossible to change it to another encoding without errors.
The question does not state that the conversion here is made from wrong encoding to correct encoding but I personally stumbled to this question just because of this situation so just a heads up for others as well.
This answer in other question gives an explanation why the conversion does not always yield correct results
https://stackoverflow.com/a/2623793/4702806
Inverse of a matrix using numpy
Inverse of a matrix using python and numpy:
>>> import numpy as np
>>> b = np.array([[2,3],[4,5]])
>>> np.linalg.inv(b)
array([[-2.5, 1.5],
[ 2. , -1. ]])
Not all matrices can be inverted. For example singular matrices are not Invertable:
>>> import numpy as np
>>> b = np.array([[2,3],[4,6]])
>>> np.linalg.inv(b)
LinAlgError: Singular matrix
Solution to singular matrix problem:
try-catch the Singular Matrix exception and keep going until you find a transform that meets your prior criteria AND is also invertable.
Intuition for why matrix inversion can't always be done; like in singular matrices:
Imagine an old overhead film projector that shines a bright light through film onto a white wall. The pixels in the film are projected to the pixels on the wall.
If I stop the film projection on a single frame, you will see the pixels of the film on the wall and I ask you to regenerate the film based on what you see. That's easy, you say, just take the inverse of the matrix that performed the projection. An Inverse of a matrix is the reversal of the projection.
Now imagine if the projector was corrupted, and I put a distorted lens in front of the film. Now multiple pixels are projected to the same spot on the wall. I asked you again to "undo this operation with the matrix inverse". You say: "I can't because you destroyed information with the lens distortion, I can't get back to where we were, because the matrix is either Singular or Degenerate."
A matrix that can be used to transform some data into other data is invertable only if the process can be reversed with no loss of information. If your matrix can't be inverted, perhaps you are defining your projection using a guess-and-check methodology rather than using a process that guarantees a non-corrupting transform.
If you're using a heuristic or anything less than perfect mathematical precision, then you'll have to define another process to manage and quarantine distortions so that programming by Brownian motion can resume.
Source:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv
How can I find non-ASCII characters in MySQL?
for this question we can also use this method :
Question from sql zoo:
Find all details of the prize won by PETER GRÜNBERG
Non-ASCII characters
ans: select*from nobel where winner like'P% GR%_%berg';
How do I disable orientation change on Android?
To lock the screen by code you have to use the actual rotation of the screen (0, 90, 180, 270) and you have to know the natural position of it, in a smartphone the natural position will be portrait and in a tablet, it will be landscape.
Here's the code (lock and unlock methods), it has been tested in some devices (smartphones and tablets) and it works great.
public static void lockScreenOrientation(Activity activity)
{
WindowManager windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Configuration configuration = activity.getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
// Search for the natural position of the device
if(configuration.orientation == Configuration.ORIENTATION_LANDSCAPE &&
(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) ||
configuration.orientation == Configuration.ORIENTATION_PORTRAIT &&
(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270))
{
// Natural position is Landscape
switch (rotation)
{
case Surface.ROTATION_0:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Surface.ROTATION_90:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case Surface.ROTATION_180:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case Surface.ROTATION_270:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
else
{
// Natural position is Portrait
switch (rotation)
{
case Surface.ROTATION_0:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Surface.ROTATION_90:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Surface.ROTATION_180:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case Surface.ROTATION_270:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
}
}
}
public static void unlockScreenOrientation(Activity activity)
{
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
Self Join to get employee manager name
As Jesse said, use self join:
SELECT
e.emp_id
, e.emp_name
, e.emp_mgr_id
, m.emp_name AS mgr_name
FROM [dbo].[tblEmployeeDetails] e
LEFT JOIN [dbo].[tblEmployeeDetails] m ON e.emp_mgr_id = m.emp_id
How to check if a string contains a substring in Bash
Extension of the question answered here How do you tell if a string contains another string in POSIX sh?:
This solution works with special characters:
# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
string="$1"
substring="$2"
if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
return 0 # $substring is in $string
else
return 1 # $substring is not in $string
fi
}
contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"
contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"
contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"
MVC controller : get JSON object from HTTP body?
you can get the json string as a param of your ActionResult
and afterwards serialize it using JSON.Net
HERE an example is being shown
in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.
HERE is an implementation using the dynamic object
How to place object files in separate subdirectory
In general, you either have to specify $(OBJDIR)
on the left hand side of all the rules that place files in $(OBJDIR)
, or you can run make from $(OBJDIR)
.
VPATH
is for sources, not for objects.
Take a look at these two links for more explanation, and a "clever" workaround.
Share data between html pages
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag
wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
mysqli or PDO - what are the pros and cons?
Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.
Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.
Git Commit Messages: 50/72 Formatting
I'd agree it is interesting to propose a particular style of working. However, unless I have the chance to set the style, I usually follow what's been done for consistency.
Taking a look at the Linux Kernel Commits, the project that started git if you like, http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=bca476139d2ded86be146dae09b06e22548b67f3, they don't follow the 50/72 rule. The first line is 54 characters.
I would say consistency matters. Set up proper means of identifying users who've made commits (user.name, user.email - especially on internal networks. User@OFFICE-1-PC-10293982811111 isn't a useful contact address). Depending on the project, make the appropriate detail available in the commit. It's hard to say what that should be; it might be tasks completed in a development process, then details of what's changed.
I don't believe users should use git one way because certain interfaces to git treat the commits in certain ways.
I should also note there are other ways to find commits. For a start, git diff
will tell you what's changed. You can also do things like git log --pretty=format:'%T %cN %ce'
to format the options of git log
.
What are the rules about using an underscore in a C++ identifier?
As for the other part of the question, it's common to put the underscore at the end of the variable name to not clash with anything internal.
I do this even inside classes and namespaces because I then only have to remember one rule (compared to "at the end of the name in global scope, and the beginning of the name everywhere else").
Changing :hover to touch/click for mobile devices
I think this simple method can achieve this goal.
With CSS you can turn off pointer event to 'none' then use jQuery to switch classes.
_x000D_
_x000D_
.item{_x000D_
pointer-events:none;_x000D_
}_x000D_
_x000D_
.item.clicked{_x000D_
pointer-events:inherit;_x000D_
}_x000D_
_x000D_
.item:hover,.item:active{_x000D_
/* Your Style On Hover Converted to Tap*/_x000D_
background:#000;_x000D_
}
_x000D_
_x000D_
_x000D_
Use jQuery to switch classed:
_x000D_
_x000D_
jQuery('.item').click(function(e){_x000D_
e.preventDefault();_x000D_
$(this).addClass('clicked')l_x000D_
});
_x000D_
_x000D_
_x000D_
How to top, left justify text in a <td> cell that spans multiple rows
try this
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
<tr style="height:100px">_x000D_
<td valign="top">January</td>_x000D_
<td valign="bottom">$100</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
use valign="top" for td style
How to create a thread?
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
CSS Calc Viewport Units Workaround?
Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.
Solution (for other browsers): box-sizing
1) Start of by setting your height as 100vh.
2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.
3) Just offset the extra padding-top with a negative margin-top
div
{
/*height: calc(100vh - 75vw);*/
height: 100vh;
margin-top: -75vw;
padding-top: 75vw;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: pink;
}
C++ code file extension? .cc vs .cpp
I've use .C and .h for source and header, respectively. One nice thing with that choice is that, on the command line, its easy to use *.[Ch]
to select all of the code files. Using .C
could be a problem on case insensitive filesystems, but if you have foo.c
and foo.C
in the same directory, you deserve what you get anyway :)
Difference between View and ViewGroup in Android
In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View
While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.
Oracle : how to subtract two dates and get minutes of the result
For those who want to substrat two timestamps (instead of dates), there is a similar solution:
SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 1440 AS minutesInBetween
FROM ...
or
SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 86400 AS secondsInBetween
FROM ...
MySQL - Using COUNT(*) in the WHERE clause
SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;
EDIT (if you just want the gids):
SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC
Android button with different background colors
As your error states, you have to define drawable attibute for the items (for some reason it is required when it comes to background definitions), so:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
<item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
<item android:drawable="@color/black"/> <!-- default -->
</selector>
Also note that drawable attribute doesn't accept raw color values, so you have to define the colors as resources. Create colors.xml file at res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#000</color>
<color name="blue">#00f</color>
<color name="red">#f00</color>
</resources>
java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?
tl;dr
Instant.now()
.toString()
2018-02-02T00:28:02.487114Z
Instant.parse(
"2018-02-02T00:28:02.487114Z"
)
java.time
The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.
The troublesome SimpleDateFormat
and Date
classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.
The equivalent to java.util.Date
is java.time.Instant
. You can even convert between them using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock
implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.
Instant instant = Instant.now() ;
Generate a String in standard ISO 8601 format.
String output = instant.toString() ;
2018-02-02T00:28:02.487114Z
To generate strings in other formats, search Stack Overflow for DateTimeFormatter
, already covered many times.
To adjust into a time zone other than UTC, use ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift
Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10
Add these extensions :
extension CGRect{
init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
self.init(x:x,y:y,width:width,height:height)
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension CGPoint{
init(_ x:CGFloat,_ y:CGFloat) {
self.init(x:x,y:y)
}
}
Then go to "Find and Replace in Workspace"
Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize
These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3
SQL, Postgres OIDs, What are they and why are they useful?
OIDs basically give you a built-in id for every row, contained in a system column (as opposed to a user-space column). That's handy for tables where you don't have a primary key, have duplicate rows, etc. For example, if you have a table with two identical rows, and you want to delete the oldest of the two, you could do that using the oid column.
OIDs are implemented using 4-byte unsigned integers. They are not unique–OID counter will wrap around at 2³²-1. OID are also used to identify data types (see /usr/include/postgresql/server/catalog/pg_type_d.h
).
In my experience, the feature is generally unused in most postgres-backed applications (probably in part because they're non-standard), and their use is essentially deprecated:
In PostgreSQL 8.1 default_with_oids is
off by default; in prior versions of
PostgreSQL, it was on by default.
The use of OIDs in user tables is
considered deprecated, so most
installations should leave this
variable disabled. Applications that
require OIDs for a particular table
should specify WITH OIDS when creating
the table. This variable can be
enabled for compatibility with old
applications that do not follow this
behavior.
How to initialize a variable of date type in java?
tl;dr
Use Instant
, replacement for java.util.Date
.
Instant.now() // Capture current moment as seen in UTC.
If you must have a Date
, convert.
java.util.Date.from( Instant.now() )
java.time
The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.
The java.time classes tend to use static factory methods rather than constructors for instantiating objects.
To get the current moment in UTC time zone:
Instant instant = Instant.now();
To get the current moment in a particular time zone:
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant
.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
enable/disable zoom in Android WebView
We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.
I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()
-method which was working with an ZoomButtonsController
-object to enable and disable the zoom controls depending on the current scale of the browser.
I searched for a method to return the ZoomButtonsController
-instance and found the getZoomButtonsController()
-method, that returned this very instance.
Although the method is declared public
, it is not documented in the WebView
-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView
-subclass to override the onTouchEvent()
-method, which triggered the controls.
public class NoZoomControllWebView extends WebView {
private ZoomButtonsController zoom_controll = null;
public NoZoomControllWebView(Context context) {
super(context);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs) {
super(context, attrs);
disableControls();
}
/**
* Disable the controls
*/
private void disableControls(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
} else {
// Use the reflection magic to make it work on earlier APIs
getControlls();
}
}
/**
* This is where the magic happens :D
*/
private void getControlls() {
try {
Class webview = Class.forName("android.webkit.WebView");
Method method = webview.getMethod("getZoomButtonsController");
zoom_controll = (ZoomButtonsController) method.invoke(this, null);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
return true;
}
}
You might want to remove the unnecessary constructors and react on probably on the exceptions.
Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).
As @jayellos pointed out in the comments, the private getZoomButtonsController()
-method is no longer existing on Android 4.0.4 and later.
However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.
I updated the example code above to do exactly that.
How do you use the "WITH" clause in MySQL?
I followed the link shared by lisachenko and found another link to this blog:
http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html
The post lays out ways of emulating the 2 uses of SQL WITH. Really good explanation on how these work to do a similar query as SQL WITH.
1) Use WITH so you don't have to perform the same sub query multiple times
CREATE VIEW D AS (SELECT YEAR, SUM(SALES) AS S FROM T1 GROUP BY YEAR);
SELECT D1.YEAR, (CASE WHEN D1.S>D2.S THEN 'INCREASE' ELSE 'DECREASE' END) AS TREND
FROM
D AS D1,
D AS D2
WHERE D1.YEAR = D2.YEAR-1;
DROP VIEW D;
2) Recursive queries can be done with a stored procedure that makes the call similar to a recursive with query.
CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
SELECT ID, NAME, MANAGER_ID, 0 AS REPORTS
FROM EMPLOYEES
WHERE ID NOT IN (SELECT MANAGER_ID FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL)
",
"
SELECT M.ID, M.NAME, M.MANAGER_ID, SUM(1+E.REPORTS) AS REPORTS
FROM EMPLOYEES M JOIN EMPLOYEES_EXTENDED E ON M.ID=E.MANAGER_ID
GROUP BY M.ID, M.NAME, M.MANAGER_ID
",
"SELECT * FROM EMPLOYEES_EXTENDED",
0,
""
);
And this is the code or the stored procedure
# Usage: the standard syntax:
# WITH RECURSIVE recursive_table AS
# (initial_SELECT
# UNION ALL
# recursive_SELECT)
# final_SELECT;
# should be translated by you to
# CALL WITH_EMULATOR(recursive_table, initial_SELECT, recursive_SELECT,
# final_SELECT, 0, "").
# ALGORITHM:
# 1) we have an initial table T0 (actual name is an argument
# "recursive_table"), we fill it with result of initial_SELECT.
# 2) We have a union table U, initially empty.
# 3) Loop:
# add rows of T0 to U,
# run recursive_SELECT based on T0 and put result into table T1,
# if T1 is empty
# then leave loop,
# else swap T0 and T1 (renaming) and empty T1
# 4) Drop T0, T1
# 5) Rename U to T0
# 6) run final select, send relult to client
# This is for *one* recursive table.
# It would be possible to write a SP creating multiple recursive tables.
delimiter |
CREATE PROCEDURE WITH_EMULATOR(
recursive_table varchar(100), # name of recursive table
initial_SELECT varchar(65530), # seed a.k.a. anchor
recursive_SELECT varchar(65530), # recursive member
final_SELECT varchar(65530), # final SELECT on UNION result
max_recursion int unsigned, # safety against infinite loop, use 0 for default
create_table_options varchar(65530) # you can add CREATE-TABLE-time options
# to your recursive_table, to speed up initial/recursive/final SELECTs; example:
# "(KEY(some_column)) ENGINE=MEMORY"
)
BEGIN
declare new_rows int unsigned;
declare show_progress int default 0; # set to 1 to trace/debug execution
declare recursive_table_next varchar(120);
declare recursive_table_union varchar(120);
declare recursive_table_tmp varchar(120);
set recursive_table_next = concat(recursive_table, "_next");
set recursive_table_union = concat(recursive_table, "_union");
set recursive_table_tmp = concat(recursive_table, "_tmp");
# Cleanup any previous failed runs
SET @str =
CONCAT("DROP TEMPORARY TABLE IF EXISTS ", recursive_table, ",",
recursive_table_next, ",", recursive_table_union,
",", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# If you need to reference recursive_table more than
# once in recursive_SELECT, remove the TEMPORARY word.
SET @str = # create and fill T0
CONCAT("CREATE TEMPORARY TABLE ", recursive_table, " ",
create_table_options, " AS ", initial_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create U
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_union, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str = # create T1
CONCAT("CREATE TEMPORARY TABLE ", recursive_table_next, " LIKE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
if max_recursion = 0 then
set max_recursion = 100; # a default to protect the innocent
end if;
recursion: repeat
# add T0 to U (this is always UNION ALL)
SET @str =
CONCAT("INSERT INTO ", recursive_table_union, " SELECT * FROM ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if max depth reached
set max_recursion = max_recursion - 1;
if not max_recursion then
if show_progress then
select concat("max recursion exceeded");
end if;
leave recursion;
end if;
# fill T1 by applying the recursive SELECT on T0
SET @str =
CONCAT("INSERT INTO ", recursive_table_next, " ", recursive_SELECT);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we are done if no rows in T1
select row_count() into new_rows;
if show_progress then
select concat(new_rows, " new rows found");
end if;
if not new_rows then
leave recursion;
end if;
# Prepare next iteration:
# T1 becomes T0, to be the source of next run of recursive_SELECT,
# T0 is recycled to be T1.
SET @str =
CONCAT("ALTER TABLE ", recursive_table, " RENAME ", recursive_table_tmp);
PREPARE stmt FROM @str;
EXECUTE stmt;
# we use ALTER TABLE RENAME because RENAME TABLE does not support temp tables
SET @str =
CONCAT("ALTER TABLE ", recursive_table_next, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
SET @str =
CONCAT("ALTER TABLE ", recursive_table_tmp, " RENAME ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
# empty T1
SET @str =
CONCAT("TRUNCATE TABLE ", recursive_table_next);
PREPARE stmt FROM @str;
EXECUTE stmt;
until 0 end repeat;
# eliminate T0 and T1
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table_next, ", ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Final (output) SELECT uses recursive_table name
SET @str =
CONCAT("ALTER TABLE ", recursive_table_union, " RENAME ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# Run final SELECT on UNION
SET @str = final_SELECT;
PREPARE stmt FROM @str;
EXECUTE stmt;
# No temporary tables may survive:
SET @str =
CONCAT("DROP TEMPORARY TABLE ", recursive_table);
PREPARE stmt FROM @str;
EXECUTE stmt;
# We are done :-)
END|
delimiter ;
JQUERY ajax passing value from MVC View to Controller
Try using the data
option of the $.ajax
function. More info here.
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatus) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
How to use export with Python on Linux
import os
import shlex
from subprocess import Popen, PIPE
os.environ.update(key=value)
res = Popen(shlex.split("cmd xxx -xxx"), stdin=PIPE, stdout=PIPE, stderr=PIPE,
env=os.environ, shell=True).communicate('y\ny\ny\n'.encode('utf8'))
stdout = res[0]
stderr = res[1]
Create a variable name with "paste" in R?
In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.
output=NULL
for(i in 1:8){
Tax=eval(as.symbol(paste("Tax",i,sep="")))
L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
h=hist(L_Data,breaks=breaks,plot=FALSE)
output=cbind(output,h$counts)
}
/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found
This solution work on my case i am using ubuntu 16.04, VirtualBox 2.7.2 and genymotion 2.7.2
Same error come in my system i have followed simple step and my problem was solve
1. $ LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
2. $ export LD_LIBRARY_PATH
3. $ sudo apt-add-repository ppa:ubuntu-toolchain-r/test
4. $ sudo apt-get update
5. $ sudo apt-get install gcc-4.9 g++-4.9
I hope this will work for you
C# : Passing a Generic Object
You're missing at least a couple of things:
Unless you're using reflection, the type arguments need to be known at compile-time, so you can't use
PrintGeneric<test2.GetType()>
... although in this case you don't need to anyway
PrintGeneric
doesn't know anything about T
at the moment, so the compiler can't find a member called T
Options:
Put a property in the ITest
interface, and change PrintGeneric
to constrain T
:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.PropertyFromInterface);
}
Put a property in the ITest
interface and remove the generics entirely:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Property : " + test.PropertyFromInterface);
}
Use dynamic typing instead of generics if you're using C# 4
Traverse all the Nodes of a JSON Object Tree with JavaScript
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail || []
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
how to change a selections options based on another select option selected?
Here is an example of what you are trying to do => fiddle
_x000D_
_x000D_
$(document).ready(function () {_x000D_
$("#type").change(function () {_x000D_
var val = $(this).val();_x000D_
if (val == "item1") {_x000D_
$("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
} else if (val == "item2") {_x000D_
$("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
} else if (val == "item3") {_x000D_
$("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
} else if (val == "item0") {_x000D_
$("#size").html("<option value=''>--select one--</option>");_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
<option value="item0">--Select an Item--</option>_x000D_
<option value="item1">item1</option>_x000D_
<option value="item2">item2</option>_x000D_
<option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
<option value="">-- select one -- </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
How to remove padding around buttons in Android?
I had the same problem and it seems that it is because of the background color of the button. Try changing the background color to another color eg:
android:background="@color/colorActive"
and see if it works. You can then define a style if you want for the button to use.
"CASE" statement within "WHERE" clause in SQL Server 2008
First off, the CASE
statement must be part of the expression, not the expression itself.
In other words, you can have:
WHERE co.DTEntered = CASE
WHEN LEN('blah') = 0
THEN co.DTEntered
ELSE '2011-01-01'
END
But it won't work the way you have written them eg:
WHERE
CASE LEN('TestPerson')
WHEN 0 THEN co.personentered = co.personentered
ELSE co.personentered LIKE '%TestPerson'
END
You may have better luck using combined OR statements like this:
WHERE (
(LEN('TestPerson') = 0
AND co.personentered = co.personentered
)
OR
(LEN('TestPerson') <> 0
AND co.personentered LIKE '%TestPerson')
)
Although, either way I'm not sure how great of a query plan you'll get. These types of shenanigans in a WHERE
clause will often prevent the query optimizer from utilizing indexes.
Can someone give an example of cosine similarity, in a very simple, graphical way?
This is a simple Python
code which implements cosine similarity.
from scipy import linalg, mat, dot
import numpy as np
In [12]: matrix = mat( [[2, 1, 0, 2, 0, 1, 1, 1],[2, 1, 1, 1, 1, 0, 1, 1]] )
In [13]: matrix
Out[13]:
matrix([[2, 1, 0, 2, 0, 1, 1, 1],
[2, 1, 1, 1, 1, 0, 1, 1]])
In [14]: dot(matrix[0],matrix[1].T)/np.linalg.norm(matrix[0])/np.linalg.norm(matrix[1])
Out[14]: matrix([[ 0.82158384]])
Is it possible to use an input value attribute as a CSS selector?
Following the currently top voted answer, I've found using a dataset / data attribute works well.
_x000D_
_x000D_
//Javascript
const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute
document.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", function() {
this.dataset.value = this.value;
console.log(this);
})
})
_x000D_
/*CSS*/
input[data-value="0.00"] {
color: red;
}
_x000D_
<!--HTML-->
<div>
<p>Input1 is programmatically set by JavaScript:</p>
<label for="input1">Input 1:</label>
<input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
<p>Try typing 0.00 inside input2:</p>
<label for="input2">Input 2:</label>
<input id="input2" value="undefined" data-value="undefined">
</div>
_x000D_
_x000D_
_x000D_
How to sum a variable by group
Since dplyr 1.0.0
, the across()
function could be used:
df %>%
group_by(Category) %>%
summarise(across(Frequency, sum))
Category Frequency
<chr> <int>
1 First 30
2 Second 5
3 Third 34
If interested in multiple variables:
df %>%
group_by(Category) %>%
summarise(across(c(Frequency, Frequency2), sum))
Category Frequency Frequency2
<chr> <int> <int>
1 First 30 55
2 Second 5 29
3 Third 34 190
And the selection of variables using select helpers:
df %>%
group_by(Category) %>%
summarise(across(starts_with("Freq"), sum))
Category Frequency Frequency2 Frequency3
<chr> <int> <int> <dbl>
1 First 30 55 110
2 Second 5 29 58
3 Third 34 190 380
Sample data:
df <- read.table(text = "Category Frequency Frequency2 Frequency3
1 First 10 10 20
2 First 15 30 60
3 First 5 15 30
4 Second 2 8 16
5 Third 14 70 140
6 Third 20 120 240
7 Second 3 21 42",
header = TRUE,
stringsAsFactors = FALSE)
Replace \n with <br />
thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
How to include vars file in a vars file with ansible?
Unfortunately, vars files do not have include statements.
You can either put all the vars into the definitions
dictionary, or add the variables as another dictionary in the same file.
If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:
---
- hosts: myhosts
vars_files:
- default_step.yml
or in a task:
---
- hosts: myhosts
tasks:
- name: include default step variables
include_vars: default_step.yml
How to get HttpRequestMessage data
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
SQL Server stored procedure Nullable parameter
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
Android - SMS Broadcast receiver
Your broadcast receiver must specify android:exported="true"
to receive broadcasts created outside your own application. My broadcast receiver is defined in the manifest as follows:
<receiver
android:name=".IncomingSmsBroadcastReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
As noted below, exported="true" is the default, so you can omit this line. I've left it in so that the discussion comments make sense.
PHP cURL HTTP PUT
In a POST method, you can put an array. However, in a PUT method, you should use http_build_query
to build the params like this:
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );
commons httpclient - Adding query string parameters to GET/POST request
If you want to add a query parameter after you have created the request, try casting the HttpRequest
to a HttpBaseRequest
. Then you can change the URI of the casted request:
HttpGet someHttpGet = new HttpGet("http://google.de");
URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
"That was easy!").build();
((HttpRequestBase) someHttpGet).setURI(uri);
How to disable a button when an input is empty?
its simple let us assume you have made an state full class by extending Component which contains following
class DisableButton extends Components
{
constructor()
{
super();
// now set the initial state of button enable and disable to be false
this.state = {isEnable: false }
}
// this function checks the length and make button to be enable by updating the state
handleButtonEnable(event)
{
const value = this.target.value;
if(value.length > 0 )
{
// set the state of isEnable to be true to make the button to be enable
this.setState({isEnable : true})
}
}
// in render you having button and input
render()
{
return (
<div>
<input
placeholder={"ANY_PLACEHOLDER"}
onChange={this.handleChangePassword}
/>
<button
onClick ={this.someFunction}
disabled = {this.state.isEnable}
/>
<div/>
)
}
}
How can I create a dynamically sized array of structs?
You've tagged this as C++ as well as C.
If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects.
#include <stdio.h>
#include <vector>
typedef std::vector<char*> words;
int main(int argc, char** argv) {
words myWords;
myWords.push_back("Hello");
myWords.push_back("World");
words::iterator iter;
for (iter = myWords.begin(); iter != myWords.end(); ++iter) {
printf("%s ", *iter);
}
return 0;
}
If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily.
#include <stdio.h>
#include <stdlib.h>
typedef struct s_words {
char* str;
struct s_words* next;
} words;
words* create_words(char* word) {
words* newWords = malloc(sizeof(words));
if (NULL != newWords){
newWords->str = word;
newWords->next = NULL;
}
return newWords;
}
void delete_words(words* oldWords) {
if (NULL != oldWords->next) {
delete_words(oldWords->next);
}
free(oldWords);
}
words* add_word(words* wordList, char* word) {
words* newWords = create_words(word);
if (NULL != newWords) {
newWords->next = wordList;
}
return newWords;
}
int main(int argc, char** argv) {
words* myWords = create_words("Hello");
myWords = add_word(myWords, "World");
words* iter;
for (iter = myWords; NULL != iter; iter = iter->next) {
printf("%s ", iter->str);
}
delete_words(myWords);
return 0;
}
Yikes, sorry for the worlds longest answer. So WRT to the "don't want to use a linked list comment":
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char** words;
size_t nWords;
size_t size;
size_t block_size;
} word_list;
word_list* create_word_list(size_t block_size) {
word_list* pWordList = malloc(sizeof(word_list));
if (NULL != pWordList) {
pWordList->nWords = 0;
pWordList->size = block_size;
pWordList->block_size = block_size;
pWordList->words = malloc(sizeof(char*)*block_size);
if (NULL == pWordList->words) {
free(pWordList);
return NULL;
}
}
return pWordList;
}
void delete_word_list(word_list* pWordList) {
free(pWordList->words);
free(pWordList);
}
int add_word_to_word_list(word_list* pWordList, char* word) {
size_t nWords = pWordList->nWords;
if (nWords >= pWordList->size) {
size_t newSize = pWordList->size + pWordList->block_size;
void* newWords = realloc(pWordList->words, sizeof(char*)*newSize);
if (NULL == newWords) {
return 0;
} else {
pWordList->size = newSize;
pWordList->words = (char**)newWords;
}
}
pWordList->words[nWords] = word;
++pWordList->nWords;
return 1;
}
char** word_list_start(word_list* pWordList) {
return pWordList->words;
}
char** word_list_end(word_list* pWordList) {
return &pWordList->words[pWordList->nWords];
}
int main(int argc, char** argv) {
word_list* myWords = create_word_list(2);
add_word_to_word_list(myWords, "Hello");
add_word_to_word_list(myWords, "World");
add_word_to_word_list(myWords, "Goodbye");
char** iter;
for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) {
printf("%s ", *iter);
}
delete_word_list(myWords);
return 0;
}
Python, Matplotlib, subplot: How to set the axis range?
Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes
or AxesSubplot
object. The functions of interest are set_autoscale_on
, set_autoscalex_on
, and set_autoscaley_on
.
In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on
property to False
. Here is a modified version of the FFT subplot snippet from your code:
fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
C++ template typedef
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
Can you do a For Each Row loop using MySQL?
In the link you provided, thats not a loop in sql...
thats a loop in programming language
they are first getting list of all distinct districts, and then for each district executing query again.
Create iOS Home Screen Shortcuts on Chrome for iOS
Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.
javascript:location.href=%22googlechrome%22+location.href.substring(4);
Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.
Source
Works for me.
getting file size in javascript
To get the file size of pages on the web I built a javascript bookmarklet to do the trick. It alerts the size in kb's. Change the alert to a prompt if you want to copy the filesize.
Here's the bookmarklet code for the alert.
<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);alert(c+' kb');">Doc Size</a>
Here's the bookmarklet code for the prompt.
<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);prompt('Page Size',c+' kb');">Doc Size</a>
See it in action at http://bookmarklets.to.g0.to/filesize.php
How to see if a directory exists or not in Perl?
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
ASP.NET MVC - Getting QueryString values
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
What's the best UI for entering date of birth?
I had tried datePicker with my user but it turn out to be a bad UI to them.
What I end up base on their request is to have 3 textbox where they can quickly type [ day ] [ month ] [ year ] :(
How to merge a transparent png image with another image using PIL
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
Tools: replace not replacing in Android manifest
I fixed same issue. Solution for me:
- add the
xmlns:tools="http://schemas.android.com/tools"
line in the manifest tag
- add
tools:replace=..
in the manifest tag
- move
android:label=...
in the manifest tag
Example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:replace="allowBackup, label"
android:allowBackup="false"
android:label="@string/all_app_name"/>
Java Date cut off time information
With Joda you can easily get the expected date.
As of version 2.7 (maybe since some previous version greater than 2.2), as a commenter notes, toDateMidnight
has been deprecated in favor or the aptly named withTimeAtStartOfDay()
, making the convenient
DateTime.now().withTimeAtStartOfDay()
possible.
Benefit added of a way nicer API.
With older versions, you can do
new DateTime(new Date()).toDateMidnight().toDate()
jQuery javascript regex Replace <br> with \n
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
How To fix white screen on app Start up?
The white background is coming from the Apptheme.You can show something useful like your application logo instead of white screen.it can be done using custom theme.in your app Theme just add
android:windowBackground=""
attribute.
The attribute value may be a image or layered list or any color.
Pagination response payload from a RESTful API
generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn"
with theses parameters, you can do it a simple request.
in the service, eg. .net
jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
from tbANyThing tt
where id > lastIdObtained
order by id
}
In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got
Passing arguments forward to another javascript function
The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments
object.
The arguments
object contains one element for each actual parameter provided to the function. When you call a
you supply three arguments: the numbers 1
, 2
, and, 3
. So, arguments
contains [1, 2, 3]
.
function a(args){
console.log(arguments) // [1, 2, 3]
b(arguments);
}
When you call b
, however, you pass exactly one argument: a
's arguments
object. So arguments
contains [[1, 2, 3]]
(i.e. one element, which is a
's arguments
object, which has properties containing the original arguments to a
).
function b(args){
// arguments are lost?
console.log(arguments) // [[1, 2, 3]]
}
a(1,2,3);
As @Nick demonstrated, you can use apply
to provide a set arguments
object in the call.
The following achieves the same result:
function a(args){
b(arguments[0], arguments[1], arguments[2]); // three arguments
}
But apply
is the correct solution in the general case.
Include headers when using SELECT INTO OUTFILE?
an example from my database
table name sensor with colums (id,time,unit)
select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM sensor
Xml serialization - Hide null values
In my case the nullable variables/elements were all String type. So, I simply performed a check and assigned them string.Empty in case of NULL. This way I got rid of the unnecessary nil and xmlns attributes (p3:nil="true" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance)
// Example:
myNullableStringElement = varCarryingValue ?? string.Empty
// OR
myNullableStringElement = myNullableStringElement ?? string.Empty
binning data in python with scipy/numpy
The Scipy (>=0.11) function scipy.stats.binned_statistic specifically addresses the above question.
For the same example as in the previous answers, the Scipy solution would be
import numpy as np
from scipy.stats import binned_statistic
data = np.random.rand(100)
bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]
Should I use scipy.pi, numpy.pi, or math.pi?
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
How Can I Override Style Info from a CSS Class in the Body of a Page?
Eli,
it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.
Also remember that in general an id is more specific than a class is more specific than an element.
Hope that helps.
-Rick
How to Convert string "07:35" (HH:MM) to TimeSpan
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.
Filter df when values matches part of a string in pyspark
When filtering a DataFrame with string values, I find that the pyspark.sql.functions
lower
and upper
come in handy, if your data could have column entries like "foo" and "Foo":
import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
enum to string in modern C++11 / C++14 / C++17 and future C++20
My answer is here.
You can get enum value names and these indices simultaneously as deque of string.
This method only needs little copy and paste and edit.
Obtained result needs type-casting from size_t to enum class type when you need enum class type value, but I think it is a very portable and powerful way to treat enum class.
enum class myenum
{
one = 0,
two,
three,
};
deque<string> ssplit(const string &_src, boost::regex &_re)
{
boost::sregex_token_iterator it(_src.begin(), _src.end(), _re, -1);
boost::sregex_token_iterator e;
deque<string> tokens;
while (it != e)
tokens.push_back(*it++);
return std::move(tokens);
}
int main()
{
regex re(",");
deque<string> tokens = ssplit("one,two,three", re);
for (auto &t : tokens) cout << t << endl;
getchar();
return 0;
}
Checking oracle sid and database name
I presume SELECT user FROM dual;
should give you the current user
and SELECT sys_context('userenv','instance_name') FROM dual;
the name of the instance
I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;
Oracle SQL : timestamps in where clause
to_timestamp()
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
to_date()
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
Example
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
Note
You never need to use to_timestamp()
on a column that is of type timestamp
.
How to force uninstallation of windows service
sc delete sericeName
Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.
Why don't self-closing script elements work?
Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml
. If you're serving XHTML as text/html
, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.
The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.
IE9 and later support XHTML 5 served with application/xhtml+xml
.
How to use code to open a modal in Angular 2?
I'm currently using Bootstrap 4.3 in Angular 8 and want to open modal window programmatically (without actually clicking on some button as the official demo shows).
Following method works for me:
The general idea is to create a button associated to a modal window.
First make sure after you click this button, it can open the modal.
Then give this button tag an id using hashtag, for example #hiddenBtn
.
In component ts file, import ViewChild from @angular/core
and write below code:
@ViewChild('hiddenBtn', {static: false}) myHiddenBtn;
After that, whenever you want to open this modal window in your component ts code, write following code to simulate click operation
this.myHiddenBtn.nativeElement.click();
SQL Server Script to create a new user
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
How generate unique Integers based on GUIDs
In a static class, keep a static const integer, then add 1 to it before every single access (using a public get property). This will ensure you cycle the whole int range before you get a non-unique value.
/// <summary>
/// The command id to use. This is a thread-safe id, that is unique over the lifetime of the process. It changes
/// at each access.
/// </summary>
internal static int NextCommandId
{
get
{
return _nextCommandId++;
}
}
private static int _nextCommandId = 0;
This will produce a unique integer value within a running process. Since you do not explicitly define how unique your integer should be, this will probably fit.
how to get GET and POST variables with JQuery?
With any server-side language, you will have to emit the POST variables into javascript.
.NET
var my_post_variable = '<%= Request("post_variable") %>';
Just be careful of empty values. If the variable you attempt to emit is actually empty, you will get a javascript syntax error. If you know it's a string, you should wrap it in quotes. If it's an integer, you may want to test to see if it actually exists before writing the line to javascript.
Can you delete data from influxdb?
Because InfluxDB is a bit painful about deletes, we use a schema that has a boolean field called "ForUse", which looks like this when posting via the line protocol (v0.9):
your_measurement,your_tag=foo ForUse=TRUE,value=123.5 1262304000000000000
You can overwrite the same measurement, tag key, and time with whatever field keys you send, so we do "deletes" by setting "ForUse" to false, and letting retention policy keep the database size under control.
Since the overwrite happens seamlessly, you can retroactively add the schema too. Noice.
Recommended way to insert elements into map
Use insert
if you want to insert a new element. insert
will not
overwrite an existing element, and you can verify that there was no
previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.
How can I convert JSON to CSV?
It is not a very smart way to do it, but I have had the same problem and this worked for me:
import csv
f = open('data.json')
data = json.load(f)
f.close()
new_data = []
for i in data:
flat = {}
names = i.keys()
for n in names:
try:
if len(i[n].keys()) > 0:
for ii in i[n].keys():
flat[n+"_"+ii] = i[n][ii]
except:
flat[n] = i[n]
new_data.append(flat)
f = open(filename, "r")
writer = csv.DictWriter(f, new_data[0].keys())
writer.writeheader()
for row in new_data:
writer.writerow(row)
f.close()
Can constructors be async?
Some of the answers involve creating a new public
method. Without doing this, use the Lazy<T>
class:
public class ViewModel
{
private Lazy<ObservableCollection<TData>> Data;
async public ViewModel()
{
Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
}
public ObservableCollection<TData> GetDataTask()
{
Task<ObservableCollection<TData>> task;
//Create a task which represents getting the data
return task.GetAwaiter().GetResult();
}
}
To use Data
, use Data.Value
.
How to detect when an @Input() value changes in Angular?
You can use a BehaviorSubject
within a facade service then subscribe to that subject in any component and when an event happens to trigger a change in data call .next()
on it. Make sure to close out those subscriptions within the on destroy lifecycle hook.
data-api.facade.ts
@Injectable({
providedIn: 'root'
})
export class DataApiFacade {
currentTabIndex: BehaviorSubject<number> = new BehaviorSubject(0);
}
some.component.ts
constructor(private dataApiFacade: DataApiFacade){}
ngOnInit(): void {
this.dataApiFacade.currentTabIndex
.pipe(takeUntil(this.destroy$))
.subscribe(value => {
if (value) {
this.currentTabIndex = value;
}
});
}
setTabView(event: MatTabChangeEvent) {
this.dataApiFacade.currentTabIndex.next(event.index);
}
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.complete();
}
How to remove array element in mongodb?
In Mongoose:
from the document:
To remove a document from a subdocument array we may pass an object
with a matching _id.
contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works
See Leonid Beschastny's answer for the correct answer.
How to increase number of threads in tomcat thread pool?
You would have to tune it according to your environment.
Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.
Say, instead of
<Connector ... maxThreads="500" acceptCount="50"
you use
<Connector ... maxThreads="300" acceptCount="150"
you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.
In any case, though, you have to do some benchmarks to really know what is best.
Return multiple values in JavaScript?
I know of two ways to do this:
1. Return as Array
2. Return as Object
Here's an example I found:
<script>
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}
// Store returned value in a variable
var all = divideNumbers(10, 2);
// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
</script>
<script>
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var obj = {
dividend: dividend,
divisor: divisor,
quotient: quotient
};
return obj;
}
// Store returned value in a variable
var all = divideNumbers(10, 2);
// Displaying individual values
alert(all.dividend); // 0utputs: 10
alert(all.divisor); // 0utputs: 2
alert(all.quotient); // 0utputs: 5
</script>
Remove a symlink to a directory
Assuming it actually is a symlink,
$ rm -d symlink
It should figure it out, but since it can't we enable the latent code that was intended for another case that no longer exists but happens to do the right thing here.
How to Iterate over a Set/HashSet without an Iterator?
Enumeration(?):
Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
{
System.out.println(e.nextElement());
}
Another way (java.util.Collections.enumeration()):
for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
{
System.out.println(e1.nextElement());
}
Java 8:
set.forEach(element -> System.out.println(element));
or
set.stream().forEach((elem) -> {
System.out.println(elem);
});
Use cell's color as condition in if statement (function)
The only easy solution that I have applied is to recreate the primary condition that do the highlights as an IF
condition and use it on the IF
formula. Something like this. Depending on the highlight condition the formula will change but I think that should be recreated (es. highlight greater than 20).
=IF(B3>20,(B3)," ")
SSL Error: unable to get local issuer certificate
If you are a linux user
Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
How to concatenate two IEnumerable<T> into a new IEnumerable<T>?
You can use below code for your solution:-
public void Linq94()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine("All numbers from both arrays:");
foreach (var n in allNumbers)
{
Console.WriteLine(n);
}
}
How can I return NULL from a generic method in C#?
Take the recommendation of the error... and either user default(T)
or new T
.
You will have to add in a comparison in your code to ensure that it was a valid match if you go that route.
Otherwise, potentially consider an output parameter for "match found".
Get the first N elements of an array?
array_slice() is best thing to try, following are the examples:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
Always show vertical scrollbar in <select>
I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.
If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.
As an example, see it here a JavaScript that make select like editable.
Function passed as template argument
Edit: Passing the operator as a reference doesnt work. For simplicity, understand it as a function pointer. You just send the pointer, not a reference.
I think you are trying to write something like this.
struct Square
{
double operator()(double number) { return number * number; }
};
template <class Function>
double integrate(Function f, double a, double b, unsigned int intervals)
{
double delta = (b - a) / intervals, sum = 0.0;
while(a < b)
{
sum += f(a) * delta;
a += delta;
}
return sum;
}
.
.
std::cout << "interval : " << i << tab << tab << "intgeration = "
<< integrate(Square(), 0.0, 1.0, 10) << std::endl;
How do I schedule a task to run at periodic intervals?
Use timer.scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
- task - task to be scheduled.
- delay - delay in milliseconds before task is to be executed.
- period - time in milliseconds between successive task executions.
Throws:
- IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
- IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
Wildcards in a Windows hosts file
I don't think that it is possible.
You anyway have to modify the apache virtualroot entries every time you add a new site and location, so it's not a big work to syncronise the new name to the Windows vhost file.
Update: please check the next answer and the comments on this answer. This answer is 6 years old and not correct anymore.
center MessageBox in parent form
But why stop with MessageBox-specific implementation? Use the class below like this:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dg;
using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
{
dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
if (dg == DialogResult.No)
{
e.Cancel = true;
}
}
The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):
(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags
, which is below)
public class DialogCenteringService : IDisposable
{
private readonly IWin32Window owner;
private readonly HookProc hookProc;
private readonly IntPtr hHook = IntPtr.Zero;
public DialogCenteringService(IWin32Window owner)
{
if (owner == null) throw new ArgumentNullException("owner");
this.owner = owner;
hookProc = DialogHookProc;
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
}
private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(hHook);
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
public void Dispose()
{
UnhookWindowsHookEx(hHook);
}
private void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
if (!success)
{
return;
}
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(owner.Handle, ref recParent);
if (!success)
{
return;
}
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
//MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
}
// some p/invoke
// ReSharper disable InconsistentNaming
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
private const int WH_CALLWNDPROCRET = 12;
// ReSharper disable EnumUnderlyingTypeIsInt
private enum CbtHookAction : int
// ReSharper restore EnumUnderlyingTypeIsInt
{
// ReSharper disable UnusedMember.Local
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
// ReSharper restore UnusedMember.Local
}
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
// ReSharper restore InconsistentNaming
}
[Flags]
public enum SetWindowPosFlags : uint
{
// ReSharper disable InconsistentNaming
/// <summary>
/// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
/// </summary>
SWP_ASYNCWINDOWPOS = 0x4000,
/// <summary>
/// Prevents generation of the WM_SYNCPAINT message.
/// </summary>
SWP_DEFERERASE = 0x2000,
/// <summary>
/// Draws a frame (defined in the window's class description) around the window.
/// </summary>
SWP_DRAWFRAME = 0x0020,
/// <summary>
/// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
/// </summary>
SWP_FRAMECHANGED = 0x0020,
/// <summary>
/// Hides the window.
/// </summary>
SWP_HIDEWINDOW = 0x0080,
/// <summary>
/// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
/// </summary>
SWP_NOACTIVATE = 0x0010,
/// <summary>
/// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
/// </summary>
SWP_NOCOPYBITS = 0x0100,
/// <summary>
/// Retains the current position (ignores X and Y parameters).
/// </summary>
SWP_NOMOVE = 0x0002,
/// <summary>
/// Does not change the owner window's position in the Z order.
/// </summary>
SWP_NOOWNERZORDER = 0x0200,
/// <summary>
/// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
/// </summary>
SWP_NOREDRAW = 0x0008,
/// <summary>
/// Same as the SWP_NOOWNERZORDER flag.
/// </summary>
SWP_NOREPOSITION = 0x0200,
/// <summary>
/// Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
/// </summary>
SWP_NOSENDCHANGING = 0x0400,
/// <summary>
/// Retains the current size (ignores the cx and cy parameters).
/// </summary>
SWP_NOSIZE = 0x0001,
/// <summary>
/// Retains the current Z order (ignores the hWndInsertAfter parameter).
/// </summary>
SWP_NOZORDER = 0x0004,
/// <summary>
/// Displays the window.
/// </summary>
SWP_SHOWWINDOW = 0x0040,
// ReSharper restore InconsistentNaming
}
OTP (token) should be automatically read from the message
Sorry for late reply but still felt like posting my answer if it helps.It works for 6 digits OTP.
@Override
public void onOTPReceived(String messageBody)
{
Pattern pattern = Pattern.compile(SMSReceiver.OTP_REGEX);
Matcher matcher = pattern.matcher(messageBody);
String otp = HkpConstants.EMPTY;
while (matcher.find())
{
otp = matcher.group();
}
checkAndSetOTP(otp);
}
Adding constants here
public static final String OTP_REGEX = "[0-9]{1,6}";
For SMS listener one can follow the below class
public class SMSReceiver extends BroadcastReceiver
{
public static final String SMS_BUNDLE = "pdus";
public static final String OTP_REGEX = "[0-9]{1,6}";
private static final String FORMAT = "format";
private OnOTPSMSReceivedListener otpSMSListener;
public SMSReceiver(OnOTPSMSReceivedListener listener)
{
otpSMSListener = listener;
}
@Override
public void onReceive(Context context, Intent intent)
{
Bundle intentExtras = intent.getExtras();
if (intentExtras != null)
{
Object[] sms_bundle = (Object[]) intentExtras.get(SMS_BUNDLE);
String format = intent.getStringExtra(FORMAT);
if (sms_bundle != null)
{
otpSMSListener.onOTPSMSReceived(format, sms_bundle);
}
else {
// do nothing
}
}
}
@FunctionalInterface
public interface OnOTPSMSReceivedListener
{
void onOTPSMSReceived(@Nullable String format, Object... smsBundle);
}
}
@Override
public void onOTPSMSReceived(@Nullable String format, Object... smsBundle)
{
for (Object aSmsBundle : smsBundle)
{
SmsMessage smsMessage = getIncomingMessage(format, aSmsBundle);
String sender = smsMessage.getDisplayOriginatingAddress();
if (sender.toLowerCase().contains(ONEMG))
{
getIncomingMessage(smsMessage.getMessageBody());
} else
{
// do nothing
}
}
}
private SmsMessage getIncomingMessage(@Nullable String format, Object aObject)
{
SmsMessage currentSMS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && format != null)
{
currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
} else
{
currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
}
return currentSMS;
}
How to check whether input value is integer or float?
Do this to distinguish that.
If for example your number is 3.1214 and stored in num but you don't know kind of num:
num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
// num is a integer
}
else
// num is float
}
In this example we see that num is not integer.
Can an Android Toast be longer than Toast.LENGTH_LONG?
Here is a custom Toast class I made using the above code:
import android.content.Context;
import android.os.CountDownTimer;
import android.widget.Toast;
public class CustomToast extends Toast {
int mDuration;
boolean mShowing = false;
public CustomToast(Context context) {
super(context);
mDuration = 2;
}
/**
* Set the time to show the toast for (in seconds)
* @param seconds Seconds to display the toast
*/
@Override
public void setDuration(int seconds) {
super.setDuration(LENGTH_SHORT);
if(seconds < 2) seconds = 2; //Minimum
mDuration = seconds;
}
/**
* Show the toast for the given time
*/
@Override
public void show() {
super.show();
if(mShowing) return;
mShowing = true;
final Toast thisToast = this;
new CountDownTimer((mDuration-2)*1000, 1000)
{
public void onTick(long millisUntilFinished) {thisToast.show();}
public void onFinish() {thisToast.show(); mShowing = false;}
}.start();
}
}
Creating an object: with or without `new`
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
What is the difference between JOIN and UNION?
Joins and unions can be used to combine data from one or more tables. The difference lies in how the data is combined.
In simple terms, joins combine data into new columns. If two tables are joined together, then the data from the first table is shown in one set of column alongside the second table’s column in the same row.
Unions combine data into new rows. If two tables are “unioned” together, then the data from the first table is in one set of rows, and the data from the second table in another set. The rows are in the same result.
asp.net mvc @Html.CheckBoxFor
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
How to avoid 'cannot read property of undefined' errors?
What you are doing raises an exception (and rightfully so).
You can always do
try{
window.a.b.c
}catch(e){
console.log("YO",e)
}
But I wouldn't, instead think of your use case.
Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?
Usually, you'd like to actually validate what sort of object you're dealing with.
Also, on a side note you should not use statements like if(a.b)
because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined
Syntax of for-loop in SQL Server
How about this:
BEGIN
Do Something
END
GO 10
... of course you could put an incremental counter inside it if you need to count.
Substitute a comma with a line break in a cell
To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):
=SUBSTITUTE(A1,",",CHAR(10))
You may have to then alter the row height to see all of the values in the cell
I've left a comment about the other part of your question
Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.
Android - border for button
create drawable/button_green.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#003000"
android:centerColor="#006000"
android:endColor="#003000"
android:angle="270" />
<corners android:radius="5dp" />
<stroke android:width="2px" android:color="#007000" />
</shape>
and point it out as @drawable/button_green
:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/button_green"
android:text="Button" />
How to handle ListView click in Android
In Kotlin, add a listener to your listView as simple as java
your_listview.setOnItemClickListener { parent, view, position, id ->
Toast.makeText(this, position, Toast.LENGTH_SHORT).show()
}
Disable output buffering
Yes, it is enabled by default. You can disable it by using the -u option on the command line when calling python.
How to make <input type="file"/> accept only these types?
for image write this
<input type=file accept="image/*">
For other,
You can use the accept attribute on your form to suggest to the browser to restrict certain types. However, you'll want to re-validate in your server-side code to make sure. Never trust what the client sends you
How do I make Git use the editor of my choice for commits?
For Windows users who want to use Kinesics Text Editor
Create a file called 'k.sh', add the following text and place in your home directory (~):
winpty "C:\Program Files (x86)\Kinesics Text Editor\x64\k.exe" $1
At the git prompt type:
git config --global core.editor ~/k.sh
ImportError: No module named 'google'
I had a similar import problem. I noticed that there was no __init__.py
file in the root of the google
package. So, I created an empty __init__.py
and now the import works.
How to create a new instance from a class object in Python
This is how you can dynamically create a class named Child
in your code, assuming Parent
already exists... even if you don't have an explicit Parent
class, you could use object
...
The code below defines __init__()
and then associates it with the class.
>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
# Initialization for the Child class
self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>
Android lollipop change navigation bar color
Here are some ways to change Navigation Bar color.
By the XML
1- values-v21/style.xml
<item name="android:navigationBarColor">@color/navigationbar_color</item>
Or if you want to do it only using the values/ folder then-
2- values/style.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<item name="android:navigationBarColor" tools:targetApi="21">@color/navigationbar_color</item>
You can also change navigation bar color By Programming.
if (Build.VERSION.SDK_INT >= 21)
getWindow().setNavigationBarColor(getResources().getColor(R.color.navigationbar_color));
By Using Compat Library-
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}
please find the link for more details- http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)
Read XML file using javascript
The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.
/**
* Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
* If a string is given, it first tries to create an XMLDomElement from the given string.
*
* @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
* @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
* @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
*/
Object.fromXML = function( source, includeRoot ) {
if( typeof source == 'string' )
{
try
{
if ( window.DOMParser )
source = ( new DOMParser() ).parseFromString( source, "application/xml" );
else if( window.ActiveXObject )
{
var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
xmlObject.async = false;
xmlObject.loadXML( source );
source = xmlObject;
xmlObject = undefined;
}
else
throw new Error( "Cannot find an XML parser!" );
}
catch( error )
{
return false;
}
}
var result = {};
if( source.nodeType == 9 )
source = source.firstChild;
if( !includeRoot )
source = source.firstChild;
while( source ) {
if( source.childNodes.length ) {
if( source.tagName in result ) {
if( result[source.tagName].constructor != Array )
result[source.tagName] = [result[source.tagName]];
result[source.tagName].push( Object.fromXML( source ) );
}
else
result[source.tagName] = Object.fromXML( source );
} else if( source.tagName )
result[source.tagName] = source.nodeValue;
else if( !source.nextSibling ) {
if( source.nodeValue.clean() != "" ) {
result = source.nodeValue.clean();
}
}
source = source.nextSibling;
}
return result;
};
String.prototype.clean = function() {
var self = this;
return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}
What is the best way to get the first letter from a string in Java, returned as a string of length 1?
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
ArrayList or List declaration in Java
List is interface and ArrayList is implemented concrete class.
It is always recommended to use.
List<String> arrayList = new ArrayList<String>();
Because here list reference is flexible. It can also hold LinkedList or Vector
object.
VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory
Taking Shiraz's idea and running with it...
In your application, are you explicitly defining a domain User Account and Password to access AD?
When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.
A VBScript example would be as follows:
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "MyDomain\MyAccount"
objConnection.Properties("Password") = "MyPassword"
objConnection.Open "Active Directory Provider"
If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.
How to call a method after a delay in Android
you can use Handler inside UIThread:
runOnUiThread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//add your code here
}
}, 1000);
}
});
String.Format for Hex
You can also pad the characters left by including a number following the X
, such as this: string.format("0x{0:X8}", string_to_modify)
, which yields "0x00000C20"
.
Debugging in Maven?
I thought I would expand on these answers for OSX and Linux folks (not that they need it):
I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.
$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found
DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.
I use a package manager for OSX and Linux so I have no idea where mvn really lives.
(I know for brief periods of time.. thanks brew.. I like that I don't know this.)
Let's see:
$ which mvn
/usr/local/bin/mvn
There you are... you little b@stard.
Now where did you get installed to:
$ ls -l /usr/local/bin/mvn
lrwxr-xr-x 1 root wheel 39 Oct 31 13:00 /
/usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn
Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn.
You cheeky little build tool. No doubt by homebrew...
Do you have your little buddy mvnDebug with you?
$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
Good. Good. Very good. All going as planned.
Now move that little b@stard where I can remember him more easily.
$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
ln: /usr/local/bin/mvnDebug: Permission denied
Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!
$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)
$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000
Internally mvnDebug uses this:
MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
So you could modify it (I usually debug on port 9090).
This blog explains how to setup Eclipse remote debugging (shudder)
http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html
Ditto Netbeans
https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a
Ditto IntelliJ
http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html
Here is some good docs on the -Xdebug command in general.
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."
"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."
-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp
Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.
Map enum in JPA with fixed values?
The best approach would be to map a unique ID to each enum type, thus avoiding the pitfalls of ORDINAL and STRING. See this post which outlines 5 ways you can map an enum.
Taken from the link above:
1&2. Using @Enumerated
There are currently 2 ways you can map enums within your JPA entities using the @Enumerated annotation. Unfortunately both EnumType.STRING and EnumType.ORDINAL have their limitations.
If you use EnumType.String then renaming one of your enum types will cause your enum value to be out of sync with the values saved in the database. If you use EnumType.ORDINAL then deleting or reordering the types within your enum will cause the values saved in the database to map to the wrong enums types.
Both of these options are fragile. If the enum is modified without performing a database migration, you could jeopodise the integrity of your data.
3. Lifecycle Callbacks
A possible solution would to use the JPA lifecycle call back annotations, @PrePersist and @PostLoad. This feels quite ugly as you will now have two variables in your entity. One mapping the value stored in the database, and the other, the actual enum.
4. Mapping unique ID to each enum type
The preferred solution is to map your enum to a fixed value, or ID, defined within the enum. Mapping to predefined, fixed value makes your code more robust. Any modification to the order of the enums types, or the refactoring of the names, will not cause any adverse effects.
5. Using Java EE7 @Convert
If you are using JPA 2.1 you have the option to use the new @Convert annotation. This requires the creation of a converter class, annotated with @Converter, inside which you would define what values are saved into the database for each enum type. Within your entity you would then annotate your enum with @Convert.
My preference: (Number 4)
The reason why I prefer to define my ID's within the enum as oppose to using a converter, is good encapsulation. Only the enum type should know of its ID, and only the entity should know about how it maps the enum to the database.
See the original post for the code example.
Specified cast is not valid.. how to resolve this
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
Getting the first character of a string with $str[0]
My only doubt would be how applicable this technique would be on multi-byte strings, but if that's not a consideration, then I suspect you're covered. (If in doubt, mb_substr()
seems an obviously safe choice.)
However, from a big picture perspective, I have to wonder how often you need to access the 'n'th character in a string for this to be a key consideration.
Max length for client ip address
Take it from someone who has tried it all three ways... just use a varchar(39)
The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.
Read the current full URL with React?
Just to add a little further documentation to this page - I have been struggling with this problem for a while.
As said above, the easiest way to get the URL is via window.location.href
.
we can then extract parts of the URL through vanilla Javascript by using let urlElements = window.location.href.split('/')
We would then console.log(urlElements)
to see the Array of elements produced by calling .split() on the URL.
Once you have found which index in the array you want to access, you can then assigned this to a variable
let urlElelement = (urlElements[0])
And now you can use the value of urlElement, which will be the specific part of your URL, wherever you want.
window.location.href doesn't redirect
In my case it is working as expected for all browsers after setting time interval.
setTimeout(function(){document.location.href = "myNextPage.html;"},100);
dplyr mutate with conditional values
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.