Can't use method return value in write context
The issue is this, you want to know if the error is not empty.
public function getError() {
return $this->error;
}
Adding a method isErrorSet() will solve the problem.
public function isErrorSet() {
if (isset($this->error) && !empty($this->error)) {
return true;
} else {
return false;
}
}
Now this will work fine with this code with no notice.
if (!($x->isErrorSet())) {
echo $x->getError();
}
setting JAVA_HOME & CLASSPATH in CentOS 6
Instructions:
- Click on the Terminal icon in the desktop panel to open a terminal
window and access the command prompt.
- Type the command
which java
to find the path to the Java
executable file.
- Type the command
su -
to become the root user.
- Type the command
vi /root/.bash_profile
to open the system
bash_profile file in the Vi text editor. You can replace vi with
your preferred text editor.
- Type
export JAVA_HOME=/usr/local/java/
at the bottom of the file.
Replace /usr/local/java
with the location found in step two.
- Save and close the bash_profile file.
- Type the command
exit
to close the root session.
- Log out of the system and log back in.
- Type the command
echo $JAVA_HOME
to ensure that the path was set
correctly.
set java_home in centos
Show and hide a View with a slide up/down animation
Here is my solution. Just get a reference to your view and call this method:
public static void animateViewFromBottomToTop(final View view){
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
final int TRANSLATION_Y = view.getHeight();
view.setTranslationY(TRANSLATION_Y);
view.setVisibility(View.GONE);
view.animate()
.translationYBy(-TRANSLATION_Y)
.setDuration(500)
.setStartDelay(200)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(final Animator animation) {
view.setVisibility(View.VISIBLE);
}
})
.start();
}
});
}
No need to do anything else =)
Angularjs simple file download causes router to redirect
in template
<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
system_update_alt
</md-icon></md-button>
in controller
$scope.export = function(){ $window.location.href = $scope.export; };
Convert 4 bytes to int
You should put it into a function like this:
public static int toInt(byte[] bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte[] bytes = new byte[]{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use readByte()
repeatedly and not worry about it otherwise;
Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
Get Today's date in Java at midnight time
Here is a Java 8 based solution, using the new java.time package (Tutorial).
If you can use Java 8 objects in your code, use LocalDateTime
:
LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
If you require legacy dates, i.e. java.util.Date
:
Convert the LocalDateTime
you created above to Date
using these conversions:
LocalDateTime
-> ZonedDateTime
-> Instant
-> Date
Call atZone(zone)
with a specified time-zone (or ZoneId.systemDefault()
for the system default time-zone) to create a ZonedDateTime
object, adjusted for DST as needed.
ZonedDateTime zdt = midnight.atZone(ZoneId.of("America/Montreal"));
Call toInstant()
to convert the ZonedDateTime
to an Instant
:
Instant i = zdt.toInstant()
Finally, call Date.from(instant)
to convert the Instant
to a Date
:
Date d1 = Date.from(i)
In summary it will look similar to this for you:
LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
Date d1 = Date.from(midnight.atZone(ZoneId.systemDefault()).toInstant());
Date d2 = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
See also section Legacy Date-Time Code (The Java™ Tutorials) for interoperability of the new java.time
functionality with legacy java.util
classes.
Open a new tab in the background?
I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.
Can I run HTML files directly from GitHub, instead of just viewing their source?
This solution only for chrome browser. I am not sure about other browser.
- Add "Modify Content-Type Options" extension in chrome browser.
- Open "chrome-extension://jnfofbopfpaoeojgieggflbpcblhfhka/options.html" url in browser.
- Add the rule for raw file url.
For example:
- URL Filter: https:///raw/master//fileName.html
- Original Type: text/plain
- Replacement Type: text/html
- Open the file browser which you added url in rule (in step 3).
JNI and Gradle in Android Studio
gradle supports ndk compilation by generating another Android.mk file with absolute paths to your sources.
NDK supports absolute paths since r9 on OSX, r9c on Windows, so you need to upgrade your NDK to r9+.
You may run into other troubles as NDK support by gradle is preliminary. If so you can deactivate the ndk compilation from gradle by setting:
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDir 'src/main/libs'
}
to be able to call ndk-build yourself and integrate libs from libs/.
btw, you have any issue compiling for x86 ? I see you haven't included it in your APP_ABI.
Apk location in New Android Studio
To help people who might search for answer to this same question, it is important to know what type of projects you are using in Studio.
Gradle
The default project type when creating new project, and the recommended one in general is Gradle.
For a new project called "Foo", the structure under the main folder will be
Foo/
settings.gradle
Foo/
build.gradle
build/
Where the internal "Foo" folder is the main module (this structure allows you to create more modules later on in the same structure without changes).
In this setup, the location of the generated APK will be under
Foo/Foo/build/apk/...
Note that each module can generate its own output, so the true output is more
Foo/*/build/apk/...
EDIT
On the newest version of the Android Studio location path for generated output is
Foo/*/build/outputs/apk/...
IntelliJ
If you are a user of IntelliJ before switching to Studio, and are importing your IntelliJ project directly, then nothing changed. The location of the output will be the same under:
out/production/...
Note: this is will become deprecated sometimes around 1.0
Eclipse
If you are importing Android Eclipse project directly, do not do this!
As soon as you have dependencies in your project (jars or Library Projects), this will not work and your project will not be properly setup.
If you have no dependencies, then the apk would be under the same location as you'd find it in Eclipse:
bin/...
However I cannot stress enough the importance of not doing this.
How to display activity indicator in middle of the iphone screen?
If you want to center the spinner using AutoLayout, do:
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[activityView startAnimating];
[self.view addSubview:activityView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0.0]];
Why use Ruby's attr_accessor, attr_reader and attr_writer?
All of the answers above are correct; attr_reader
and attr_writer
are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.
React navigation goBack() and update parent state
If you are using redus
you can create an action to store data and check the value in parent Component
or you can use AsyncStorage
.
But I think it's better to passing only JSON-serializable
params, because if someday you want to save state of navigation, its not very easy.
Also note react-navigation
has this feature in experimental
https://reactnavigation.org/docs/en/state-persistence.html
Each param, route, and navigation state must be fully
JSON-serializable for this feature to work. This means that your
routes and params must contain no functions, class instances, or
recursive data structures.
I like this feature in Development Mode and when I pass params as function I simply can't use it
Overwriting txt file in java
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
How do I remove the passphrase for the SSH key without having to create a new key?
On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.
ssh-keygen -K
Add this to ~/.ssh/config
UseKeychain yes
Find a pair of elements from an array whose sum equals a given number
Nice solution from Codeaddict. I took the liberty of implementing a version of it in Ruby:
def find_sum(arr,sum)
result ={}
h = Hash[arr.map {|i| [i,i]}]
arr.each { |l| result[l] = sum-l if h[sum-l] && !result[sum-l] }
result
end
To allow duplicate pairs (1,5), (5,1) we just have to remove the && !result[sum-l]
instruction
Best way to add Activity to an Android project in Eclipse?
You can use the "New Class" dialog, but that leaves other steps you need to do by hand (e.g. adding an entry to the manifest file). If you want those steps to be automated, you can create the activity via the manifest editor like this:
- Double click on AndroidManifest.xml in the package explorer.
- Click on the "Application" tab of the manifest editor
- Click on "Add.." under the "Application Nodes" heading (bottom left of the screen)
- Choose Activity from the list in the dialog that pops up (if you have the option, you want to create a new top-level element)
- Click on the "Name*" link under the "Attributes for" header (bottom right of the window) to create a class for the new activity.
When you click Finish from the new class dialog, it'll take you to your new activity class so you can start coding.
Five steps might seem a lot, but I'm just trying to be extra detailed here so that it's clear. It's pretty quick when you actually do it.
Live Video Streaming with PHP
PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.
For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.
Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.
PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).
Hope this helps.
Simple PHP form: Attachment to email (code golf)
PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.
You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.
Login to Microsoft SQL Server Error: 18456
I got this error after creating a new sysadmin user under my SQL instance.
My admin user was created under a specific domain
MyOrganization/useradmin
Using useradmin on a disconnected environment allows you to create other users using SQL Server authentication, but as soon as you try to login you get
Microsoft SQL Server Error: 18456
To fix the problem, try to connect again to your Organization network and create the user while you are connected and then you can get disconnected and will work.
Checkbox angular material checked by default
If you are using Reactive form you can set it to default like this:
In the form model, set the value to false. So if it's checked its value will be true else false
let form = this.formBuilder.group({
is_known: [false]
})
//In HTML
<mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:
You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.
For XLS file: HSSFWorkbook
& HSSFSheet
For XLSX file: XSSFSheet
& XSSFSheet
So in place of XSSFWorkbook
use HSSFWorkbook
and in place of XSSFSheet
use HSSFSheet
.
So your code should look like this after the changes are made:
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Installation Issue with matplotlib Python
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
- I assume you have installed the pip matplotlib, there is a directory in your root called
~/.matplotlib
.
- Create a file
~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
How do I convert dmesg timestamp to custom date format?
you will need to reference the "btime" in /proc/stat, which is the Unix epoch time when the system was latest booted. Then you could base on that system boot time and then add on the elapsed seconds given in dmesg to calculate timestamp for each events.
How to pass parameters on onChange of html select
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
Swift convert unix time to date and time
Anyway @Nate Cook's answer is accepted but I would like to improve it with better date format.
with Swift 2.2, I can get desired formatted date
//TimeStamp
let timeInterval = 1415639000.67457
print("time interval is \(timeInterval)")
//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)
//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is = \(dateString)")
the result is
time interval is 1415639000.67457
formatted date is = 10, November 2014 17:03:PM
Save text file UTF-8 encoded with VBA
I found the answer on the web:
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk
Certainly not as I expected...
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?
In the context of Drupal, the difference will depend whether clean URLs are on or not.
With them off, $_SERVER['REQUEST_URI']
will have the full path of the page as called w/ /index.php
, while $_GET["q"]
will just have what is assigned to q
.
With them on, they will be nearly identical w/o other arguments, but $_GET["q"]
will be missing the leading /
. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.
getDate with Jquery Datepicker
I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle
$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2010, 1 - 1, 1),
maxDate:new Date(2010, 12 - 1, 31),
altField: '#datepicker_value',
onSelect: function(){
var day1 = $("#datepicker").datepicker('getDate').getDate();
var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
$('#page_output').html(str_output);
}
});
});
How do I check if file exists in jQuery or pure JavaScript?
I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
It seems to work great, hope this helps someone!
IF EXISTS in T-SQL
There's no need for "else" in this case:
IF EXISTS(SELECT * FROM table1 WHERE Name='John' ) return 1
return 0
Instagram how to get my user id from username?
Although it's not listed on the API doc page anymore, I found a thread that mentions that you can use self
in place of user-id
for the users/{user-id}
endpoint and it'll return the currently authenticated user's info.
So, users/self
is the same as an explicit call to users/{some-user-id}
and contains the user's id as part of the payload. Once you're authenticated, just make a call to users/self
and the result will include the currently authenticated user's id, like so:
{
"data": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://snoopdogg.com",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}
while ($row = mysql_fetch_array($result)) - how many loops are being performed?
For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows()
.
For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach
language construct does: it goes through the body of the loop for each entry in the array $row
. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)
).
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Create a pointer to two-dimensional array
Here you wanna make a pointer to the first element of the array
uint8_t (*matrix_ptr)[20] = l_matrix;
With typedef, this looks cleaner
typedef uint8_t array_of_20_uint8_t[20];
array_of_20_uint8_t *matrix_ptr = l_matrix;
Then you can enjoy life again :)
matrix_ptr[0][1] = ...;
Beware of the pointer/array world in C, much confusion is around this.
Edit
Reviewing some of the other answers here, because the comment fields are too short to do there. Multiple alternatives were proposed, but it wasn't shown how they behave. Here is how they do
uint8_t (*matrix_ptr)[][20] = l_matrix;
If you fix the error and add the address-of operator &
like in the following snippet
uint8_t (*matrix_ptr)[][20] = &l_matrix;
Then that one creates a pointer to an incomplete array type of elements of type array of 20 uint8_t. Because the pointer is to an array of arrays, you have to access it with
(*matrix_ptr)[0][1] = ...;
And because it's a pointer to an incomplete array, you cannot do as a shortcut
matrix_ptr[0][0][1] = ...;
Because indexing requires the element type's size to be known (indexing implies an addition of an integer to the pointer, so it won't work with incomplete types). Note that this only works in C
, because T[]
and T[N]
are compatible types. C++ does not have a concept of compatible types, and so it will reject that code, because T[]
and T[10]
are different types.
The following alternative doesn't work at all, because the element type of the array, when you view it as a one-dimensional array, is not uint8_t
, but uint8_t[20]
uint8_t *matrix_ptr = l_matrix; // fail
The following is a good alternative
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
You access it with
(*matrix_ptr)[0][1] = ...;
matrix_ptr[0][0][1] = ...; // also possible now
It has the benefit that it preserves the outer dimension's size. So you can apply sizeof on it
sizeof (*matrix_ptr) == sizeof(uint8_t) * 10 * 20
There is one other answer that makes use of the fact that items in an array are contiguously stored
uint8_t *matrix_ptr = l_matrix[0];
Now, that formally only allows you to access the elements of the first element of the two dimensional array. That is, the following condition hold
matrix_ptr[0] = ...; // valid
matrix_ptr[19] = ...; // valid
matrix_ptr[20] = ...; // undefined behavior
matrix_ptr[10*20-1] = ...; // undefined behavior
You will notice it probably works up to 10*20-1
, but if you throw on alias analysis and other aggressive optimizations, some compiler could make an assumption that may break that code. Having said that, i've never encountered a compiler that fails on it (but then again, i've not used that technique in real code), and even the C FAQ has that technique contained (with a warning about its UB'ness), and if you cannot change the array type, this is a last option to save you :)
How to time Java program execution speed
final long startTime = System.currentTimeMillis();
for (int i = 0; i < length; i++) {
// Do something
}
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime));
Check if all checkboxes are selected
This is how I achieved it in my code:
if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
$('.citycontainer').hide();
}else{
$('.citycontainer').show();
}
SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'
Turns out you can't use the root
user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root
anymore and have to do sudo mysql -u root
instead.
That also means that it will no longer work if you're using the root
user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.
See this answer for more details.
Remove characters from a String in Java
Kotlin Solution
Kotlin has a built-in function for this, removeSuffix
(Documentation)
var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"
If the suffix does not exist in the string, it just returns the original
var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"
You can also check out removePrefix
and removeSurrounding
which are similar
Diff files present in two different directories
If you specifically don't want to compare contents of files and only check which one are not present in both of the directories, you can compare lists of files, generated by another command.
diff <(find DIR1 -printf '%P\n' | sort) <(find DIR2 -printf '%P\n' | sort) | grep '^[<>]'
-printf '%P\n'
tells find
to not prefix output paths with the root directory.
I've also added sort
to make sure the order of files will be the same in both calls of find
.
The grep
at the end removes information about identical input lines.
How to detect READ_COMMITTED_SNAPSHOT is enabled?
Neither on SQL2005 nor 2012 does DBCC USEROPTIONS
show is_read_committed_snapshot_on
:
Set Option Value
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
Adding one day to a date
<?php
$stop_date = '2009-09-30 20:24:00';
echo 'date before day adding: ' . $stop_date;
$stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day'));
echo 'date after adding 1 day: ' . $stop_date;
?>
For PHP 5.2.0+, you may also do as follows:
$stop_date = new DateTime('2009-09-30 20:24:00');
echo 'date before day adding: ' . $stop_date->format('Y-m-d H:i:s');
$stop_date->modify('+1 day');
echo 'date after adding 1 day: ' . $stop_date->format('Y-m-d H:i:s');
How to store command results in a shell variable?
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
How to update only one field using Entity Framework?
You have basically two options:
- go the EF way all the way, in that case, you would
- load the object based on the
userId
provided - the entire object gets loaded
- update the
password
field
- save the object back using the context's
.SaveChanges()
method
In this case, it's up to EF how to handle this in detail. I just tested this, and in the case I only change a single field of an object, what EF creates is pretty much what you'd create manually, too - something like:
`UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId`
So EF is smart enough to figure out what columns have indeed changed, and it will create a T-SQL statement to handle just those updates that are in fact necessary.
- you define a stored procedure that does exactly what you need, in T-SQL code (just update the
Password
column for the given UserId
and nothing else - basically executes UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId
) and you create a function import for that stored procedure in your EF model and you call this function instead of doing the steps outlined above
How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?
There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:
<profile>
<id>runSonar</id>
<activation>
<property>
<name>runSonar</name>
<value>true</value>
</property>
</activation>
<properties>
<sonar.language>java</sonar.language>
<sonar.host.url>http://sonar.url</sonar.host.url>
<sonar.login>tokenX</sonar.login>
<sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
<sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
<jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<append>true</append>
<destFile>${jacoco.destFile}</destFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.2</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar
you get the complete coverage.
The magic here is maven.multiModuleProjectDirectory
. This folder is always the folder where you started your maven build.
Error: stray '\240' in program
As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:
iconv -f utf-8 -t ascii//translit input.c > output.c
Android: How to handle right to left swipe gestures
Here is simple Android Code for detecting gesture direction
In MainActivity.java
and activity_main.xml
, write the following code:
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.GestureStroke;
import android.gesture.Prediction;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity implements
OnGesturePerformedListener {
GestureOverlayView gesture;
GestureLibrary lib;
ArrayList<Prediction> prediction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lib = GestureLibraries.fromRawResource(MainActivity.this,
R.id.gestureOverlayView1);
gesture = (GestureOverlayView) findViewById(R.id.gestureOverlayView1);
gesture.addOnGesturePerformedListener(this);
}
@Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<GestureStroke> strokeList = gesture.getStrokes();
// prediction = lib.recognize(gesture);
float f[] = strokeList.get(0).points;
String str = "";
if (f[0] < f[f.length - 2]) {
str = "Right gesture";
} else if (f[0] > f[f.length - 2]) {
str = "Left gesture";
} else {
str = "no direction";
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<android.gesture.GestureOverlayView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
xmlns:android2="http://schemas.android.com/apk/res/android"
android:id="@+id/gestureOverlayView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android1:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw gesture"
android:textAppearance="?android:attr/textAppearanceMedium" />
</android.gesture.GestureOverlayView>
Play a Sound with Python
After the play() command add a delay of say 10 secs or so, it'll work
import pygame
import time
pygame.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
time.sleep(10)
This also plays .mp3 files.
Detecting Back Button/Hash Change in URL
The answers here are all quite old.
In the HTML5 world, you should the use onpopstate
event.
window.onpopstate = function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
Or:
window.addEventListener('popstate', function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.
In Python, how do I determine if an object is iterable?
try:
#treat object as iterable
except TypeError, e:
#object is not actually iterable
Don't run checks to see if your duck really is a duck to see if it is iterable or not, treat it as if it was and complain if it wasn't.
How to find the difference in days between two dates?
on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.
DATE=$(echo `date`)
DATENOW=$(echo `date -d "$DATE" +%j`)
DATECOMING=$(echo `date -d "20131220" +%j`)
THEDAY=$(echo `expr $DATECOMING - $DATENOW`)
echo $THEDAY
Emulate a 403 error page
I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:
- Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
- Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
- now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work)
The code below should be your first line!
<?php header('HTTP/1.0 403 Forbidden');
$contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
exit($contents);
Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.
Project vs Repository in GitHub
Fact 1: Projects and Repositories were always synonyms on GitHub.
Fact 2: This is no longer the case.
There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.
Not any more.
Currently repos and projects refer to a different kinds of entities that have separate APIs:
Since then it is no longer correct to call the repo a project or vice versa.
Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.
The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.
The term that is usually unambiguous is "project board".
What can we learn from the API
The first endpoint in the documentation of the Projects API:
is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:
{
"message": "Projects are disabled for this repo",
"documentation_url": "https://developer.github.com/v3"
}
which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.
There are some other interesting endpoints:
- Create a repository project -
POST /repos/:owner/:repo/projects
- Create an organization project -
POST /orgs/:org/projects
but there is no:
Create a user's project - POST /users/:user/projects
Which leads us to another difference:
1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations
or, more importantly:
1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users
See also:
I know it's confusing. I tried to explain it as precisely as I could.
Want to show/hide div based on dropdown box selection
you have error in your code unexpected token
.use:
$('#purpose').on('change', function () {
if (this.value == '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
Demo
Update: You can narrow down the code using .toggle()
$('#purpose').on('change', function () {
$("#business").toggle(this.value == '1');
});
How do you print in a Go test using the "testing" package?
For example,
package verbose
import (
"fmt"
"testing"
)
func TestPrintSomething(t *testing.T) {
fmt.Println("Say hi")
t.Log("Say bye")
}
go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
v_test.go:10: Say bye
PASS
ok so/v 0.002s
Command go
Description of testing flags
-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.
Package testing
func (*T) Log
func (c *T) Log(args ...interface{})
Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.
clear form values after submission ajax
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
What is "pass-through authentication" in IIS 7?
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
Overlapping Views in Android
Also, take a look at FrameLayout
, that's how the Camera's Gallery application implements the Zoom buttons overlay.
How do I reference the input of an HTML <textarea> control in codebehind?
You are not using a .NET control for your text area. Either add runat="server"
to the HTML TextArea control or use a .NET control:
Try this:
<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />
Then reference it in your codebehind:
message.Body = TextArea1.Text;
How to import existing *.sql files in PostgreSQL 8.4?
From the command line:
psql -f 1.sql
psql -f 2.sql
From the psql
prompt:
\i 1.sql
\i 2.sql
Note that you may need to import the files in a specific order (for example: data definition before data manipulation). If you've got bash
shell (GNU/Linux, Mac OS X, Cygwin) and the files may be imported in the alphabetical order, you may use this command:
for f in *.sql ; do psql -f $f ; done
Here's the documentation of the psql
application (thanks, Frank): http://www.postgresql.org/docs/current/static/app-psql.html
Android simple alert dialog
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
How can I add C++11 support to Code::Blocks compiler?
- Go to
Toolbar -> Settings -> Compiler
- In the
Selected compiler
drop-down menu, make sure GNU GCC Compiler
is selected
- Below that, select the
compiler settings
tab and then the compiler flags
tab underneath
- In the list below, make sure the box for "
Have g++ follow the C++11 ISO C++ language standard [-std=c++11]
" is checked
- Click
OK
to save
COPY with docker but with exclusion
For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):
Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.
COPY [^n]* # All files that don't start with 'n'
COPY n[^o]* # All files that start with 'n', but not 'no'
COPY no[^d]* # All files that start with 'no', but not 'nod'
Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.
What does 'stale file handle' in Linux mean?
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
Update .NET web service to use TLS 1.2
We actually just upgraded a .NET web service to 4.6 to allow TLS 1.2.
What Artem is saying were the first steps we've done. We recompiled the framework of the web service to 4.6 and we tried change the registry key to enable TLS 1.2, although this didn't work: the connection was still in TLS 1.0. Also, we didn't want to disallow SLL 3.0, TLS 1.0 or TLS 1.1 on the machine: other web services could be using this; we rolled-back our changes on the registry.
We actually changed the Web.Config files to tell IIS: "hey, run me in 4.6 please".
Here's the changes we added in the web.config + recompilation in .NET 4.6:
<system.web>
<compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
<!--Added this httpRuntime -->
<httpRuntime targetFramework="4.6" />
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
And the connection changed to TLS 1.2, because IIS is now running the web service in 4.6 (told explicitly) and 4.6 is using TLS 1.2 by default.
Java Multiple Inheritance
you can have an interface hierarchy and then extend your classes from selected interfaces :
public interface IAnimal {
}
public interface IBird implements IAnimal {
}
public interface IHorse implements IAnimal {
}
public interface IPegasus implements IBird,IHorse{
}
and then define your classes as needed, by extending a specific interface :
public class Bird implements IBird {
}
public class Horse implements IHorse{
}
public class Pegasus implements IPegasus {
}
Determine whether a key is present in a dictionary
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
How to keep keys/values in same order as declared?
from collections import OrderedDict
OrderedDict((word, True) for word in words)
contains
OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])
If the values are True
(or any other immutable object), you can also use:
OrderedDict.fromkeys(words, True)
How do you enable mod_rewrite on any OS?
Just a fyi for people enabling mod_rewrite on Debian with Apache2:
To check whether mod_rewrite is enabled:
Look in mods_enabled for a link to the module by running
ls /etc/apache2/mods-enabled | grep rewrite
If this outputs rewrite.load
then the module is enabled. (Note: your path to apache2 may not be /etc/, though it's likely to be.)
To enable mod_rewrite if it's not already:
Enable the module (essentially creates the link we were looking for above):
a2enmod rewrite
Reload all apache config files:
service apache2 restart
How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?
Edit: After updating to appcompat-v7:22.1.1 and using AppCompatActivity
instead of ActionBarActivity
my styles.xml looks like:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Note: This means I am using a Toolbar
provided by the framework (NOT included in an XML file).
This worked for me:
styles.xml file:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
Update: A quote from Gabriele Mariotti's blog.
With the new Toolbar you can apply a style and a theme.
They are different!
The style is local to the Toolbar view, for example the background color.
The app:theme is instead global to all ui elements inflated in the Toolbar, for example the color of the title and icons.
How to add java plugin for Firefox on Linux?
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
JavaScript: How do I print a message to the error console?
A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)
My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...
jquery get height of iframe content when loaded
This's a jQuery free solution that can work with SPA inside the iframe
document.getElementById('iframe-id').addEventListener('load', function () {
let that = this;
setTimeout(function () {
that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
}, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});
How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?
Using this approach with Response.js is better. Response.resize triggers on every window resize where crossover will only be triggered if breakpoint is changed
Response.create({
prop : "width",
breakpoints : [1200, 992, 768, 480, 320, 0]
});
Response.crossover('width', function() {
if (Response.band(1200)) {
// 1200+
} else if (Response.band(992)) {
// 992+
} else if (Response.band(768)) {
// 768+
} else if (Response.band(480)) {
//480+
} else {
// 0->320
}
});
Response.ready(function() {
$(window).trigger('resize');
});
Setting the JVM via the command line on Windows
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.
Type java -help for the options. In particular, see:
-version:<value>
require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
Shell script to check if file exists
Wildcards aren't expanded inside quoted strings. And when wildcard is expanded, it's returned unchanged if there are no matches, it doesn't expand into an empty string. Try:
output="$(ls home/edward/bank1/fiche/Test* 2>/dev/null)"
if [ -n "$output" ]
then echo "Found one"
else echo "Found none"
fi
If the wildcard expanded to filenames, ls
will list them on stdout
; otherwise it will print an error on stderr
, and nothing on stdout. The contents of stdout
are assigned to output
.
if [ -n "$output" ]
tests whether $output
contains anything.
Another way to write this would be:
if [ $(ls home/edward/bank1/fiche/Test* 2>/dev/null | wc -l) -gt 0 ]
Generating random numbers in C
Or, to get a pseudo-random int in the range 0 to 19,
for example, you could use the higher bits like this:
j = ((rand() >> 15) % 20;
How to add a constant column in a Spark DataFrame?
In spark 2.2 there are two ways to add constant value in a column in DataFrame:
1) Using lit
2) Using typedLit
.
The difference between the two is that typedLit
can also handle parameterized scala types e.g. List, Seq, and Map
Sample DataFrame:
val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")
+---+----+
| id|col1|
+---+----+
| 0| a|
| 1| b|
+---+----+
1) Using lit
: Adding constant string value in new column named newcol:
import org.apache.spark.sql.functions.lit
val newdf = df.withColumn("newcol",lit("myval"))
Result:
+---+----+------+
| id|col1|newcol|
+---+----+------+
| 0| a| myval|
| 1| b| myval|
+---+----+------+
2) Using typedLit
:
import org.apache.spark.sql.functions.typedLit
df.withColumn("newcol", typedLit(("sample", 10, .044)))
Result:
+---+----+-----------------+
| id|col1| newcol|
+---+----+-----------------+
| 0| a|[sample,10,0.044]|
| 1| b|[sample,10,0.044]|
| 2| c|[sample,10,0.044]|
+---+----+-----------------+
How do I make bootstrap table rows clickable?
That code transforms any bootstrap table row that has data-href
attribute set into a clickable element
Note: data-href
attribute is a valid tr
attribute (HTML5), href
attributes on tr element are not.
$(function(){
$('.table tr[data-href]').each(function(){
$(this).css('cursor','pointer').hover(
function(){
$(this).addClass('active');
},
function(){
$(this).removeClass('active');
}).click( function(){
document.location = $(this).attr('data-href');
}
);
});
});
Error You must specify a region when running command aws ecs list-container-instances
Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add
"--profile" option.
For example:
Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,
[profile playground]
region=us-east-1
then, use something like below
aws ecs list-container-instances --cluster default --profile playground
Stack Memory vs Heap Memory
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
I cannot start SQL Server browser
go to Services, find SQL Server Browser, right click --> Properties --> General tab --> Startup Type --> select automatic . Then go back to configuration management, start it.
How to create a Custom Dialog box in android?
I am posting the kotlin code that I am using and it works fine for me. you can also set click listener for dialog buttons.
this is my XML code:
layout_custom_alert_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="ltr"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:id="@+id/view6"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@color/colorPrimary" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/view6"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp">
<TextView
android:id="@+id/txt_alert_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
tools:text="are you sure?"
android:textAlignment="center"
android:textColor="@android:color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_alert_positive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView2"
android:layout_marginTop="8dp"
android:background="@android:color/transparent"
tools:text="yes"
android:textColor="@color/colorPrimaryDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/btn_alert_negative"
app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />
<Button
android:id="@+id/btn_alert_negative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@android:color/transparent"
tools:text="no"
android:textColor="@color/colorPrimaryDark"
app:layout_constraintEnd_toStartOf="@+id/btn_alert_positive"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
mAlertDialog.kt
class mAlertDialog(context: Context) {
private val btn_positive : Button
private val btn_negative : Button
private val txt_alert_title : TextView
private val dialog : AlertDialog
init {
val view = LayoutInflater.from(context).inflate(R.layout.layout_custom_alert_dialog,null)
val dialog_builder = AlertDialog.Builder(context)
dialog_builder.setView(view)
btn_negative = view.findViewById(R.id.btn_alert_negative)
btn_positive = view.findViewById(R.id.btn_alert_positive)
txt_alert_title = view.findViewById(R.id.txt_alert_title)
dialog = dialog_builder.create()
}
fun show()
{
dialog.show()
}
fun setPositiveClickListener(listener :onClickListener)
{
btn_positive.setOnClickListener { v ->
listener.onClick(btn_positive)
dialog.dismiss()
}
}
fun setNegativeClickListener(listener: onClickListener)
{
btn_negative.setOnClickListener { v ->
listener.onClick(btn_negative)
dialog.dismiss()
}
}
fun setPoitiveButtonText(text : String)
{
btn_positive.text = text
}
fun setNegativeButtonText(text : String)
{
btn_negative.text = text
}
fun setAlertTitle(title : String)
{
txt_alert_title.text = title
}
}
interface for click listeners:
onClickListener.kt
interface onClickListener{
fun onClick(view : View)
}
Sample Usage
val dialog = mAlertDialog(context)
dialog.setNegativeButtonText("no i dont")
dialog.setPoitiveButtonText("yes is do")
dialog.setAlertTitle("do you like this alert dialog?")
dialog.setPositiveClickListener(object : onClickListener {
override fun onClick(view: View) {
Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show()
}
})
dialog.setNegativeClickListener(object : onClickListener {
override fun onClick(view: View) {
Toast.makeText(context, "no", Toast.LENGTH_SHORT).show()
}
})
dialog.show()
I hope, this will help you!
Are string.Equals() and == operator really same?
There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).
This evidence supports Jon Skeet's answer.
Code:
[TestMethod]
public void StringEqualsMethodVsOperator()
{
string s1 = new StringBuilder("string").ToString();
string s2 = new StringBuilder("string").ToString();
Debug.WriteLine("string a = \"string\";");
Debug.WriteLine("string b = \"string\";");
TryAllStringComparisons(s1, s2);
s1 = null;
s2 = null;
Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
Debug.WriteLine(string.Empty);
Debug.WriteLine("string a = null;");
Debug.WriteLine("string b = null;");
TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- string.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => string.Equals(a, b), s1, s2);
Try((a, b) => string.Equals((object)a, b), s1, s2);
Try((a, b) => string.Equals(a, (object)b), s1, s2);
Try((a, b) => string.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- object.Equals --");
Debug.WriteLine(string.Empty);
Try((a, b) => object.Equals(a, b), s1, s2);
Try((a, b) => object.Equals((object)a, b), s1, s2);
Try((a, b) => object.Equals(a, (object)b), s1, s2);
Try((a, b) => object.Equals((object)a, (object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a.Equals(b) --");
Debug.WriteLine(string.Empty);
Try((a, b) => a.Equals(b), s1, s2);
Try((a, b) => a.Equals((object)b), s1, s2);
Try((a, b) => ((object)a).Equals(b), s1, s2);
Try((a, b) => ((object)a).Equals((object)b), s1, s2);
Debug.WriteLine(string.Empty);
Debug.WriteLine("-- a == b --");
Debug.WriteLine(string.Empty);
Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
T3 out1;
Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
bool success = true;
out1 = default(T3);
try
{
out1 = tryFunc.Compile()(in1, in2);
Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
}
catch (Exception ex)
{
Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
success = false;
catchFunc(ex);
}
return success;
}
Output:
string a = "string";
string b = "string";
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True
-- a == b --
(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------
string a = null;
string b = null;
-- string.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- object.Equals --
Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True
-- a.Equals(b) --
a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
-- a == b --
(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True
How do I grant read access for a user to a database in SQL Server?
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Can you style html form buttons with css?
You can achieve your desired through easily by CSS :-
HTML
<input type="submit" name="submit" value="Submit Application" id="submit" />
CSS
#submit {
background-color: #ccc;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius:6px;
color: #fff;
font-family: 'Oswald';
font-size: 20px;
text-decoration: none;
cursor: pointer;
border:none;
}
#submit:hover {
border: none;
background:red;
box-shadow: 0px 0px 1px #777;
}
DEMO
Custom edit view in UITableViewCell while swipe left. Objective-C or Swift
This has support for both title and image.
For iOS 11 and afterwards:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(
style: .normal,
title: "My Title",
handler: { (action, view, completion) in
//do what you want here
completion(true)
})
action.image = UIImage(named: "My Image")
action.backgroundColor = .red
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
Also, similar method is available for leadingSwipeActions
Source:
https://developer.apple.com/videos/play/wwdc2017/201/ (Talks about this at around 16 mins time)
https://developer.apple.com/videos/play/wwdc2017/204/ (Talks about this at around 23 mins time)
Open Facebook page from Android app?
You can open the facebook app on button click as follows:-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startNewActivity("com.facebook.katana");
}
});
}
public void startNewActivity( String packageName)
{
Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null)
{
// we found the activity
// now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
// bring user to the market
// or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id="+packageName));
startActivity(intent);
}
}
How to detect when WIFI Connection has been established in Android?
I have two methods to detect WIFI connection receiving the application context:
1)my old method
public boolean isConnectedWifi1(Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
&& ni.isConnected()) {
return true;
}
}
}
return false;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return false;
}
2)my New method (I´m currently using this method):
public boolean isConnectedWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return networkInfo.isConnected();
}
How to make an executable JAR file?
A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main
Class is in the jar file. Example code would be as follows.
public class JarExample {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// your logic here
}
});
}
}
Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF
). For example,
Manifest-Version: 1.0
Main-Class: JarExample
Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)
jar cfm jarexample.jar jexample.mf *.class
It will create executable jarexample.jar.
List passed by ref - help me explain this behaviour
This link will help you in understanding pass by reference in C#.
Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.
For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.
If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.
(Edit: this is the updated version of the documentation linked above.)
Handling urllib2's timeout? - Python
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
Writing to CSV with Python adds blank lines
The way you use the csv
module changed in Python 3 in several respects (docs), at least with respect to how you need to open the file. Anyway, something like
import csv
with open('test.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Me', 'You'],
['293', '219'],
['54', '13']]
a.writerows(data)
should work.
How do I run Google Chrome as root?
Just replace following line
exec -a "$0" "$HERE/chrome" "$@"
with
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir
all things will be right.
How can I render Partial views in asp.net mvc 3?
Create your partial view something like:
@model YourModelType
<div>
<!-- HTML to render your object -->
</div>
Then in your view use:
@Html.Partial("YourPartialViewName", Model)
If you do not want a strongly typed partial view remove the @model YourModelType
from the top of the partial view and it will default to a dynamic
type.
Update
The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/
in the path below.
@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
Simple way to find if two different lists contain exactly the same elements?
I know this is an old thread, but none of the other answers fully solved my use case (I guess Guava Multiset might do the same, but there is no example here). Please excuse my formatting. I am still new to posting on stack exchange. Additionally let me know if there are any errors
Lets say you have List<T>
a and List<T>
b and you want to check if they are equal with the following conditions:
1) O(n) expected running time
2) Equality is defined as: For all elements in a or b, the number of times the element occurs in a is equal to the number of times the element occurs in b. Element equality is defined as T.equals()
private boolean listsAreEquivelent(List<? extends Object> a, List<? extends Object> b) {
if(a==null) {
if(b==null) {
//Here 2 null lists are equivelent. You may want to change this.
return true;
} else {
return false;
}
}
if(b==null) {
return false;
}
Map<Object, Integer> tempMap = new HashMap<>();
for(Object element : a) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
tempMap.put(element, 1);
} else {
tempMap.put(element, currentCount+1);
}
}
for(Object element : b) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
return false;
} else {
tempMap.put(element, currentCount-1);
}
}
for(Integer count : tempMap.values()) {
if(count != 0) {
return false;
}
}
return true;
}
Running time is O(n) because we are doing O(2*n) insertions into a hashmap and O(3*n) hashmap selects. I have not fully tested this code, so beware :)
//Returns true:
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("B","A","A"));
listsAreEquivelent(null,null);
//Returns false:
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("B","A","B"));
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("A","B"));
listsAreEquivelent(Arrays.asList("A","A","B"),null);
How to update column with null value
Remember to look if your column can be null. You can do that using
mysql> desc my_table;
If your column cannot be null, when you set the value to null it will be the cast value to it.
Here a example
mysql> create table example ( age int not null, name varchar(100) not null );
mysql> insert into example values ( null, "without num" ), ( 2 , null );
mysql> select * from example;
+-----+-------------+
| age | name |
+-----+-------------+
| 0 | without num |
| 2 | |
+-----+-------------+
2 rows in set (0.00 sec)
mysql> select * from example where age is null or name is null;
Empty set (0.00 sec)
How to find all occurrences of a substring?
When looking for a large amount of key words in a document, use flashtext
from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)
Flashtext runs faster than regex on large list of search words.
Write objects into file with Node.js
obj
is an array in your example.
fs.writeFileSync(filename, data, [options]) requires either String
or Buffer
in the data parameter. see docs.
Try to write the array in a string format:
// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8');
Or:
// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');
edit: The reason you see the array in your example is because node's implementation of console.log
doesn't just call toString
, it calls util.format
see console.js source
String parsing in Java with delimiter tab "\t" using split
String.split
implementations will have serious limitations if the data in a tab-delimited field itself contains newline, tab and possibly " characters.
TAB-delimited formats have been around for donkey's years, but format is not standardised and varies. Many implementations don't escape characters (newlines and tabs) appearing within a field. Rather, they follow CSV conventions and wrap any non-trivial fields in "double quotes". Then they escape only double-quotes. So a "line" could extend over multiple lines.
Reading around I heard "just reuse apache tools", which sounds like good advice.
In the end I personally chose opencsv. I found it light-weight, and since it provides options for escape and quote characters it should cover most popular comma- and tab- delimited data formats.
Example:
CSVReader tabFormatReader = new CSVReader(new FileReader("yourfile.tsv"), '\t');
How to generate XML from an Excel VBA macro?
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
jquery append div inside div with id and manipulate
It's just the wrong order
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('#box').append(e);
e.attr('id', 'myid');
Append first and then access/set attr.
How to establish ssh key pair when "Host key verification failed"
This issue arises when the host key is expired or changed. you can remove the keys that host is using and try to ssh again, so that you are adding new key that is known to both client and server.
You can check the keys associated with your hosts with cat /.ssh/known_hosts
. Now, You can remove the hosts keys manually or using the ssh-keygen option. You can do either of the following option.
Manual removal of keys
vim /.ssh/known_hosts
delete the key that is associated with your host.
Remove key using ssh-keygen
ssh-keygen -R your_host_or_host_ip
This will remove your key associated with the host.
Now, you can ssh to your host as usual and you will be asked if you want to continue to this host. Once your enter yes, this host will be added to your/.ssh/known_hosts with updated key. By now, you should be your host.
declaring a priority_queue in c++ with a custom comparator
The accepted answer makes you believe that you must use a class or a std::function
as comparator. This is not true! As cute_ptr's answer shows, you can pass a function pointer to the constructor. However, the syntax to do so is much simpler than shown there:
class Node;
bool Compare(Node a, Node b);
std::priority_queue<Node, std::vector<Node>, decltype(&Compare)> openSet(Compare);
That is, there is no need to explicitly encode the function's type, you can let the compiler do that for you using decltype
.
This is very useful if the comparator is a lambda. You cannot specify the type of a lambda in any other way than using decltype
. For example:
auto compare = [](Node a, Node b) { return a.foo < b.foo; }
std::priority_queue<Node, std::vector<Node>, decltype(compare)> openSet(compare);
calling Jquery function from javascript
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
Read file line by line using ifstream in C++
Although there is no need to close the file manually but it is good idea to do so if the scope of the file variable is bigger:
ifstream infile(szFilePath);
for (string line = ""; getline(infile, line); )
{
//do something with the line
}
if(infile.is_open())
infile.close();
Why does JPA have a @Transient annotation?
Because they have different meanings. The @Transient
annotation tells the JPA provider to not persist any (non-transient
) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient
property and still serialize it.
Unable to load DLL 'SQLite.Interop.dll'
In the Nuget package of SQLLite Core there is a the file System.Data.SQLite.Core.targets . Just include this in all projects that use the this library and all libraries that used your library.
In yours .csproj or .vbproj files add:
Every time you compile in your bin will added x86 and x64 directory with the SQLite.Interop.dll file.
Case insensitive searching in Oracle
From Oracle 12c R2 you could use COLLATE operator
:
The COLLATE operator determines the collation for an expression. This operator enables you to override the collation that the database would have derived for the expression using standard collation derivation rules.
The COLLATE operator takes one argument, collation_name, for which you can specify a named collation or pseudo-collation. If the collation name contains a space, then you must enclose the name in double quotation marks.
Demo:
CREATE TABLE tab1(i INT PRIMARY KEY, name VARCHAR2(100));
INSERT INTO tab1(i, name) VALUES (1, 'John');
INSERT INTO tab1(i, name) VALUES (2, 'Joe');
INSERT INTO tab1(i, name) VALUES (3, 'Billy');
--========================================================================--
SELECT /*csv*/ *
FROM tab1
WHERE name = 'jOHN' ;
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI = 'jOHN' ;
/*
"I","NAME"
1,"John"
*/
SELECT /*csv*/ *
FROM tab1
WHERE name LIKE 'j%';
-- no rows selected
SELECT /*csv*/ *
FROM tab1
WHERE name COLLATE BINARY_CI LIKE 'j%';
/*
"I","NAME"
1,"John"
2,"Joe"
*/
db<>fiddle demo
How can I edit a .jar file?
Here's what I did:
- Extracted the files using WinRAR
- Made my changes to the extracted files
- Opened the original JAR file with WinRAR
- Used the ADD button to replace the files that I modified
That's it. I have tested it with my Nokia and it's working for me.
How do I install PyCrypto on Windows?
So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".
You need to install msys package under MinGW
and add following entries in your PATH env variable.
C:\MinGW\bin
C:\MinGW\msys\1.0\bin
[This is where you will find chmod executable]
Then run your command from normal windows command prompt.
CSS3 transition doesn't work with display property
Made some changes, but I think I got the effect you want using visibility
. http://jsfiddle.net/9dsGP/49/
I also made these changes:
position: absolute; /* so it doesn't expand the button background */
top: calc(1em + 8px); /* so it's under the "button" */
left:8px; /* so it's shifted by padding-left */
width: 182px; /* so it fits nicely under the button, width - padding-left - padding-right - border-left-width - border-right-width, 200 - 8 - 8 - 1 - 1 = 182 */
Alternatively, you could put .content as a sibling of .button, but I didn't make an example for this.
How do I request and receive user input in a .bat and use it to run a certain program?
echo off
setlocal
SET AREYOUSURE = N
:PROMPT
set /P AREYOUSURE=Update Release Files (Y/N)?
if /I %AREYOUSURE% NEQ Y GOTO END
set /P AREYOUSURE=Are You Sure you want to Update Release Files (Y/N)?
if /I %AREYOUSURE% NEQ Y GOTO END
echo Copying New Files
:END
This is code I use regularly. I have noticed in the examples in this blog that quotes are used. If the test line is changed to use quotes the test is invalid.
if /I %AREYOUSURE% NEQ "Y" GOTO END
I have tested on XP, Vista, Win7 and Win8. All fail when quotes are used.
How do I get the key at a specific index from a Dictionary in Swift?
You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)
let dict = ["c": 123, "d": 045, "a": 456]
for (index, entry) in enumerate(dict) {
println(index) // 0 1 2
println(entry) // (d, 45) (c, 123) (a, 456)
}
If you want to sort first..
var sortedKeysArray = sorted(dict) { $0.0 < $1.0 }
println(sortedKeysArray) // [(a, 456), (c, 123), (d, 45)]
var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]
then iterate.
for (index, entry) in enumerate(sortedKeysArray) {
println(index) // 0 1 2
println(entry.0) // a c d
println(entry.1) // 456 123 45
}
If you want to create an ordered dictionary, you should look into Generics.
constant pointer vs pointer on a constant value
The first is a constant pointer to a char and the second is a pointer to a constant char. You didn't touch all the cases in your code:
char * const pc1 = &a; /* You can't make pc1 point to anything else */
const char * pc2 = &a; /* You can't dereference pc2 to write. */
*pc1 = 'c' /* Legal. */
*pc2 = 'c' /* Illegal. */
pc1 = &b; /* Illegal, pc1 is a constant pointer. */
pc2 = &b; /* Legal, pc2 itself is not constant. */
jQuery: get the file name selected from <input type="file" />
It is just such simple as writing:
$('input[type=file]').val()
Anyway, I suggest using name or ID attribute to select your input.
And with event, it should look like this:
$('input[type=file]').change(function(e){
$in=$(this);
$in.next().html($in.val());
});
Concatenate in jQuery Selector
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
How to upgrade safely php version in wamp server
WAMP server generally provide addond for different php/mysql versions. However you mentioned you have downloaded latest wamp server. As of now, latest Wamp server v2.5 provide PHP version 5.5.12
So you need to upgrade it manually as follow:
- Download binaries on php.net
- Extract all files in a new folder : C:/wamp/bin/php/php5.5.27/
- Copy the wampserver.conf from another php folder (like php/php5.5.12/) to the new folder
- Rename php.ini-development file to phpForApache.ini
- Done ! Restart WampServer (>Right Mouseclick on trayicon >Exit)
Although not asked, I'd recommend to vagrant/puppet or docker for local development. Check puphpet.com for details. It has slight learning curve but it will give you much better control of different versions of every tool.
How to read a file into vector in C++?
1.
In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2.
You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
Iterating through all the cells in Excel VBA or VSTO 2005
For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.
For Excel 2003, this MSDN article is a good place to start.
Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective
You'll basically need to do the following:
- Start the Excel application.
- Open the Excel workbook.
- Retrieve the worksheet from the workbook by name or index.
- Iterate through all the Cells in the worksheet which were retrieved as a range.
- Sample (untested) code excerpt below for the last step.
Excel.Range allCellsRng;
string lowerRightCell = "IV65536";
allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
foreach (Range cell in allCellsRng)
{
if (null == cell.Value2 || isBlank(cell.Value2))
{
// Do something.
}
else if (isText(cell.Value2))
{
// Do something.
}
else if (isNumeric(cell.Value2))
{
// Do something.
}
}
For Excel 2007, try this MSDN reference.
Does `anaconda` create a separate PYTHONPATH variable for each new environment?
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/
directory, or Scripts\
on Windows).
The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.
Slidedown and slideup layout with animation
I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.
Refer to the link for more details: https://github.com/mancj/SlideUp-Android
To set up the library(copied from the ReadMe portion of its Github page on request):
Get SlideUp library
Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
maven { url "https://maven.google.com" } // or google() in AS 3.0
}
}
Add the dependency (in the Module gradle)
dependencies {
compile 'com.github.mancj:SlideUp-Android:2.2.1'
compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}
To add the SlideUp into your project, follow these three simple steps:
Step 1:
create any type of layout
<LinearLayout
android:id="@+id/slideView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Step 2:
Find that view in your activity/fragment
View slideView = findViewById(R.id.slideView);
Step 3:
Create a SlideUp object and pass in your view
slideUp = new SlideUpBuilder(slideView)
.withStartState(SlideUp.State.HIDDEN)
.withStartGravity(Gravity.BOTTOM)
//.withSlideFromOtherView(anotherView)
//.withGesturesEnabled()
//.withHideSoftInputWhenDisplayed()
//.withInterpolator()
//.withAutoSlideDuration()
//.withLoggingEnabled()
//.withTouchableAreaPx()
//.withTouchableAreaDp()
//.withListeners()
//.withSavedState()
.build();
You may also refer to the sample project on the link. I found it quite useful.
How to install Android Studio on Ubuntu?
add a repository,
sudo apt-add-repository ppa:maarten-fonville/android-studio
sudo apt-get update
Then install using the command below:
sudo apt-get install android-studio
HTML input time in 24 format
Tested!
In Windows -> control panel -> Region -> Additional Settings -> Time -> Short Time:
Format your time as HH:mm
in the format
hh = 12 hours
HH = 24 hours
mm = minutes
tt = AM or PM
so to get the required result the format should be HH:mm and not hh:mm tt
How to put Google Maps V2 on a Fragment using ViewPager
Latest stuff with getMapAsync
instead of the deprecated one.
1. check manifest for
<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxxxxxxxxxxxxxxxxxxxxxx"/>
You can get the API Key for your app by registering your app at Google Cloud Console
. Register your app as Native Android App
2. in your fragment layout .xml add FrameLayout(not fragment):
<FrameLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_weight="2"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/mapwhere" />
or whatever height you want
3. In onCreateView in your fragment
private SupportMapFragment mSupportMapFragment;
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null)
{
mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
googleMap.getUiSettings().setAllGesturesEnabled(true);
-> marker_latlng // MAKE THIS WHATEVER YOU WANT
CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.moveCamera(cameraUpdate);
}
}
});
Create a folder and sub folder in Excel VBA
Another simple version working on PC:
Sub CreateDir(strPath As String)
Dim elm As Variant
Dim strCheckPath As String
strCheckPath = ""
For Each elm In Split(strPath, "\")
strCheckPath = strCheckPath & elm & "\"
If Len(Dir(strCheckPath, vbDirectory)) = 0 Then MkDir strCheckPath
Next
End Sub
Scrolling to element using webdriver?
There is another option to scroll page to required element if element has "id"
attribute
If you want to navigate to page and scroll down to element with @id
, it can be done automatically by adding #element_id
to URL...
Example
Let's say we need to navigate to Selenium Waits documentation and scroll page down to "Implicit Wait" section. We can do
driver.get('https://selenium-python.readthedocs.io/waits.html')
and add code for scrolling...OR use
driver.get('https://selenium-python.readthedocs.io/waits.html#implicit-waits')
to navigate to page AND scroll page automatically to element with id="implicit-waits"
(<div class="section" id="implicit-waits">...</div>
)
How to style an asp.net menu with CSS
I don't know why all the answers over here are so confusing. I found a quite simpler one. Use a css class for the asp:menu, say, mainMenu and all the menu items under this will be "a tags" when rendered into HTML. So you just have to provide :hover property to those "a tags" in your CSS.
See below for the example:
<asp:Menu ID="mnuMain" Orientation="Horizontal" runat="server" Font-Bold="True" Width="100%" CssClass="mainMenu">
<Items>
<asp:MenuItem Text="Home"></asp:MenuItem>
<asp:MenuItem Text="About Us"></asp:MenuItem>
</Items>
</asp:Menu>
And in the CSS, write:
.mainMenu { background:#900; }
.mainMenu a { color:#fff; }
.mainMenu a:hover { background:#c00; color:#ff9; }
I hope this helps. :)
Assembly - JG/JNLE/JL/JNGE after CMP
Addition and subtraction in two's complement is the same for signed and unsigned numbers
The key observation is that CMP is basically subtraction, and:
In two's complement (integer representation used by x86), signed and unsigned addition are exactly the same operation
This allows for example hardware developers to implement it more efficiently with just one circuit.
So when you give input bytes to the x86 ADD instruction for example, it does not care if they are signed or not.
However, ADD does set a few flags depending on what happened during the operation:
carry: unsigned addition or subtraction result does not fit in bit size, e.g.: 0xFF + 0x01 or 0x00 - 0x01
For addition, we would need to carry 1 to the next level.
sign: result has top bit set. I.e.: is negative if interpreted as signed.
overflow: input top bits are both 0 and 0 or 1 and 1 and output inverted is the opposite.
I.e. signed operation changed sigedness in an impossible way (e.g. positive + positive or negative
We can then interpret those flags in a way that makes comparison match our expectations for signed or unsigned numbers.
This interpretation is exactly what JA vs JG and JB vs JL do for us!
Code example
Here is GNU GAS a code snippet to make this more concrete:
/* 0x0 ==
*
* * 0 in 2's complement signed
* * 0 in 2's complement unsigned
*/
mov $0, %al
/* 0xFF ==
*
* * -1 in 2's complement signed
* * 255 in 2's complement unsigned
*/
mov $0xFF, %bl
/* Do the operation "Is al < bl?" */
cmp %bl, %al
Note that AT&T syntax is "backwards": mov src, dst
. So you have to mentally reverse the operands for the condition codes to make sense with cmp
. In Intel syntax, this would be cmp al, bl
After this point, the following jumps would be taken:
- JB, because 0 < 255
- JNA, because !(0 > 255)
- JNL, because !(0 < -1)
- JG, because 0 > -1
Note how in this particular example the signedness mattered, e.g. JB is taken but not JL.
Runnable example with assertions.
Equals / Negated versions like JLE / JNG are just aliases
By looking at the Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2 section "Jcc - Jump if Condition Is Met" we see that the encodings are identical, for example:
Opcode Instruction Description
7E cb JLE rel8 Jump short if less or equal (ZF=1 or SF ? OF).
7E cb JNG rel8 Jump short if not greater (ZF=1 or SF ? OF).
How to convert strings into integers in Python?
See this function
def parse_int(s):
try:
res = int(eval(str(s)))
if type(res) == int:
return res
except:
return
Then
val = parse_int('10') # Return 10
val = parse_int('0') # Return 0
val = parse_int('10.5') # Return 10
val = parse_int('0.0') # Return 0
val = parse_int('Ten') # Return None
You can also check
if val == None: # True if input value can not be converted
pass # Note: Don't use 'if not val:'
How can I change image tintColor in iOS and WatchKit
iOS
For an iOS app, in Swift 3, 4 or 5:
theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
For Swift 2:
theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
theImageView.tintColor = UIColor.redColor()
Meanwhile, the modern Objective-C solution is:
theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];
Watchkit
In WatchKit for Apple Watch apps, you can set the tint color for a template image.
- You must add your image to an Asset Catalog in your WatchKit App, and set the image set to be rendered as a Template Image in the Attributes Inspector. Unlike for an iPhone app, you cannot set the template rendering in code in the WatchKit Extension at present.
- Set that image to be used in your WKInterfaceImage in interface builder for your app
- Create an IBOutlet in your WKInterfaceController for the WKInterfaceImage called 'theImage'...
To then set the tint color in Swift 3 or 4:
theImage.setTintColor(UIColor.red)
Swift 2:
theImage.setTintColor(UIColor.redColor())
To then set the tint color in Objective-C:
[self.theImage setTintColor:[UIColor redColor]];
If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied. If you have not set a Global Tint, theImage
will be tinted light blue by default when used as a template image.
Multiple Updates in MySQL
Yes ..it is possible using INSERT ON DUPLICATE KEY UPDATE sql statement..
syntax:
INSERT INTO table_name (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c)
How do I change the UUID of a virtual disk?
The following worked for me:
run VBoxManage internalcommands sethduuid "VDI/VMDK file" twice (the first time is just to conveniently generate an UUID, you could use any other UUID generation method instead)
open the .vbox file in a text editor
replace the UUID found in Machine uuid="{...}" with the UUID you got when you ran sethduuid the first time
replace the UUID found in HardDisk uuid="{...}" and in Image uuid="{}" (towards the end) with the UUID you got when you ran sethduuid the second time
How to stop docker under Linux
if you have no systemctl and started the docker daemon by:
sudo service docker start
you can stop it by:
sudo service docker stop