What is the preferred Bash shebang?
Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang
#!/bin/sh -
(it can also be two dashes, i.e. --
) ends bash options everything after will be treated as filenames and arguments.
Using the env
command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use
#!/usr/bin/env bash
Or for whatever the language such as for Perl
#!/usr/bin/env perl
Be sure to look at the man
pages for bash
:
man bash
and env
:
man env
Note: On Debian and Debian-based systems, like Ubuntu, sh
is linked to dash
not bash
. As all system scripts use sh
. This allows bash to grow and the system to stay stable, according to Debian.
Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.
Why do you need to put #!/bin/bash at the beginning of a script file?
The shebang is a directive to the loader to use the program which is specified after the #!
as the interpreter for the file in question when you try to execute it. So, if you try to run a file called foo.sh
which has #!/bin/bash
at the top, the actual command that runs is /bin/bash foo.sh
. This is a flexible way of using different interpreters for different programs. This is something implemented at the system level and the user level API is the shebang convention.
It's also worth knowing that the shebang is a magic number - a human readable one that identifies the file as a script for the given interpreter.
Your point about it "working" even without the shebang is only because the program in question is a shell script written for the same shell as the one you are using. For example, you could very well write a javascript file and then put a #! /usr/bin/js
(or something similar) to have a javascript "Shell script".
Should I put #! (shebang) in Python scripts, and what form should it take?
If you have different modules installed and need to use a specific
python install, then shebang appears to be limited at first. However,
you can do tricks like the below to allow the shebang to be invoked
first as a shell script and then choose python. This is very flexible
imo:
#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
echo Using preferred python $PREFERRED_PYTHON
exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
echo Using alternative python $ALTERNATIVE_PYTHON
exec $ALTERNATIVE_PYTHON "$0" "$@"
else
echo Using fallback python $FALLBACK_PYTHON
exec python3 "$0" "$@"
fi
exit 127
'''
__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())
Or better yet, perhaps, to facilitate code reuse across multiple python scripts:
#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''
and then select.sh has:
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
CHOSEN_PYTHON=$FALLBACK_PYTHON
fi
What does the line "#!/bin/sh" mean in a UNIX shell script?
It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.
#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl <-- perl script
#!/usr/bin/php <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.
Most scripting languages tend to interpret a line starting with #
as comment and will ignore the following !/usr/bin/whatever
portion, which might otherwise cause a syntax error in the interpreted language.
What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?
I find it useful, because when I didn't know about env, before I started to write script I was doing this:
type nodejs > scriptname.js #or any other environment
and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env
is very useful. Maybe there are details with this, but this is my reason
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to know installed Oracle Client is 32 bit or 64 bit?
None of the links above about lib and lib32 folder worked for me with Oracle Client 11.2.0 But I found this on the OTN community:
As far as inspecting a client install to try to tell if it's 32 bit or
64 bit, you can check the registry, a 32 bit home will be located in
HKLM>Software>WOW6432Node>Oracle, whereas a 64 bit home will be in
HKLM>Software>Oracle.
Bootstrap 3: Text overlay on image
Set the position to absolute; to move the caption area in the correct position
CSS
.post-content {
background: none repeat scroll 0 0 #FFFFFF;
opacity: 0.5;
margin: -54px 20px 12px;
position: absolute;
}
Bootply
Get Android shared preferences value in activity/normal class
You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.
A sample code to retrieve values from sharedPreferences you can use the following set of code,
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));
How do I format XML in Notepad++?
OK, here is how I did it in Notepad++:
- Plugins
- Plugin manager
- Show plugin manager
- Check XML tools
- Install
- Restart Notepad++
- Open XML file
- Plugins
- XML tools
- Pretty print (XML only -- with line breaks)
iOS download and save image inside app
Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire
:
func dowloadAndSaveFile(from url: URL) {
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(url.lastPathComponent)
return (documentsURL, [.removePreviousFile])
}
let request = SessionManager.default.download(url, method: .get, to: destination)
request.validate().responseData { response in
switch response.result {
case .success:
if let destinationURL = response.destinationURL {
print(destinationURL)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
How to overlay images
Here's a JQuery Technique with semi-transparent background.
HTML
<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
<title>Image Gallery</title>
</head>
<body>
<h1>Image Gallery</h1>
<ul id="imageGallery">
<li><a href="images/refferal_machine.png"><img src="images/refferal_machine.png" width="100" alt="Refferal Machine By Matthew Spiel"></a></li>
<li><a href="images/space-juice.png"><img src="images/space-juice.png" width="100" alt="Space Juice by Mat Helme"></a></li>
<li><a href="images/education.png"><img src="images/education.png" width="100" alt="Education by Chris Michel"></a></li>
<li><a href="images/copy_mcrepeatsalot.png"><img src="images/copy_mcrepeatsalot.png" width="100" alt="Wanted: Copy McRepeatsalot by Chris Michel"></a></li>
<li><a href="images/sebastian.png"><img src="images/sebastian.png" width="100" alt="Sebastian by Mat Helme"></a></li>
<li><a href="images/skill-polish.png"><img src="images/skill-polish.png" width="100" alt="Skill Polish by Chris Michel"></a></li>
<li><a href="images/chuck.png"><img src="images/chuck.png" width="100" alt="Chuck by Mat Helme"></a></li>
<li><a href="images/library.png"><img src="images/library.png" width="100" alt="Library by Tyson Rosage"></a></li>
<li><a href="images/boat.png"><img src="images/boat.png" width="100" alt="Boat by Griffin Moore"></a></li>
<li><a href="images/illustrator_foundations.png"><img src="images/illustrator_foundations.png" width="100" alt="Illustrator Foundations by Matthew Spiel"></a></li>
<li><a href="images/treehouse_shop.jpg"><img src="images/treehouse_shop.jpg" width="100" alt="Treehouse Shop by Eric Smith"></a></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
CSS
/** Start Coding Here **/
#overlay {
background:rgba(0,0,0,0.7);
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
display:none;
text-align:center;
}
#overlay img {
margin-top: 10%;
}
#overlay p {
color:white;
}
app.js
var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");
// 1. Capture the click event on a link to an image
$("#imageGallery a").click(function(event){
event.preventDefault();
var imageLocation = $(this).attr("href");
// 1.1 Show the overlay.
$overlay.show();
// 1.2 Update overlay with the image linked in the link
$image.attr("src", imageLocation);
// 1.3 Get child's alt attribute and set caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
// 2. Add overlay
$("body").append($overlay);
// 2.1 An image to overlay
$overlay.append($image);
// 2.2 A caption to overlay
$overlay.append($caption);
});
//When overlay is clicked
$overlay.click(function(){
//Hide the overlay
$overlay.hide();
});
Regular expression to extract text between square brackets
(?<=\[).+?(?=\])
Will capture content without brackets
(?<=\[)
- positive lookbehind for [
.*?
- non greedy match for the content
(?=\])
- positive lookahead for ]
EDIT: for nested brackets the below regex should work:
(\[(?:\[??[^\[]*?\]))
Login to website, via C#
You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.
There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").
POSTing to the login form
Form posts are easy to simulate, it's just a case of formatting your post data as follows:
field1=value1&field2=value2
Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
Here's an example of what you should see in the Set-cookie header for your login form:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
GETting the page behind the login form
Now you can perform your GET request to a page that you need to be logged in for.
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
EDIT:
If you need to view the results of the first POST, you can recover the HTML it returned with:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Place this directly below cookieHeader = resp.Headers["Set-cookie"];
and then inspect the string held in pageSource.
How can I count the number of characters in a Bash variable
Use the wc utility with the print the byte counts (-c
) option:
$ SO="stackoverflow"
$ echo -n "$SO" | wc -c
13
You'll have to use the do not output the trailing newline (-n
) option for echo
. Otherwise, the newline character will also be counted.
T-SQL split string based on delimiter
The examples above work fine when there is only one delimiter, but it doesn't scale well for multiple delimiters. Note that this will only work for SQL Server 2016 and above.
/*Some Sample Data*/
DECLARE @mytable TABLE ([id] VARCHAR(10), [name] VARCHAR(1000));
INSERT INTO @mytable
VALUES ('1','John/Smith'),('2','Jane/Doe'), ('3','Steve'), ('4','Bob/Johnson')
/*Split based on delimeter*/
SELECT P.id, [1] 'FirstName', [2] 'LastName', [3] 'Col3', [4] 'Col4'
FROM(
SELECT A.id, X1.VALUE, ROW_NUMBER() OVER (PARTITION BY A.id ORDER BY A.id) RN
FROM @mytable A
CROSS APPLY STRING_SPLIT(A.name, '/') X1
) A
PIVOT (MAX(A.[VALUE]) FOR A.RN IN ([1],[2],[3],[4],[5])) P
Create dataframe from a matrix
Using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df <- as_data_frame(mat) %>% # convert the matrix to a data frame
gather(name, val, C_0:C_1) %>% # convert the data frame from wide to long
select(name, time, val) # reorder the columns
df
# A tibble: 6 x 3
name time val
<chr> <dbl> <dbl>
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
Warning: #1265 Data truncated for column 'pdd' at row 1
You are most likely pushing a string 'NULL'
to the table, rather then an actual NULL
, but other things may be going on as well, an illustration:
mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
| NULL |
+------------+
2 rows in set (0.00 sec)
Operation Not Permitted when on root - El Capitan (rootless disabled)
Correct solution is to copy or install to /usr/local/bin
not /usr/bin
.This is due to System Integrity Protection (SIP). SIP makes /usr/bin
read-only but leaves /usr/local
as read-write.
SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.
As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."
float:left; vs display:inline; vs display:inline-block; vs display:table-cell;
I usually use float: left;
and add overflow: auto;
to solve the collapsing parent problem (as to why this works, overflow: auto
will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden
works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height
property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.
The reason I don't use display: table-cell
is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.
The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.
converting json to string in python
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
DateTime.TryParse issue with dates of yyyy-dd-MM format
From DateTime on msdn:
Type: System.DateTime% When this method returns, contains the DateTime
value equivalent to the date and time contained in s, if the
conversion succeeded, or MinValue if the conversion failed. The
conversion fails if the s parameter is null, is an empty string (""),
or does not contain a valid string representation of a date and time.
This parameter is passed uninitialized.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt"
instead.
How to send FormData objects with Ajax-requests in jQuery?
JavaScript:
function submitForm() {
var data1 = new FormData($('input[name^="file"]'));
$.each($('input[name^="file"]')[0].files, function(i, file) {
data1.append(i, file);
});
$.ajax({
url: "<?php echo base_url() ?>employee/dashboard2/test2",
type: "POST",
data: data1,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log("PHP Output:");
console.log(data);
});
return false;
}
PHP:
public function upload_file() {
foreach($_FILES as $key) {
$name = time().$key['name'];
$path = 'upload/'.$name;
@move_uploaded_file($key['tmp_name'], $path);
}
}
How to plot all the columns of a data frame in R
You can jump through hoops and convert your solution to a lapply
, sapply
or apply
call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.
If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo
package as it handles ordered data like this very well indeed.
require(zoo)
set.seed(1)
## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it
plot(datz)
Which gives:
How to stretch in width a WPF user control to its window?
This worked for me.
don't assign any width or height to the UserControl and define row and column definition in the parent window.
<UserControl x:Class="MySampleApp.myUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<Grid>
</Grid>
</UserControl>
<Window xmlns:MySampleApp="clr-namespace:MySampleApp" x:Class="MySampleApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="auto" Width="auto" MinWidth="1000" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<MySampleApp:myUC Grid.Column="0" Grid.Row="0" />
</Grid>
How to insert double and float values to sqlite?
enter code here
package in.my;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
private static final String DATABASE_NAME = "helper.db";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
private static final String Table_Record =
"create table Student (_id integer primary key autoincrement, "
+ "Name text not null,rate integer, Phone text not null,Salary text not null,email text not null,address text not null,des text not null,qual text not null,doj text not null);";
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(Table_Record);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return DBAdapter.this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public long insertTitle(String name,String phone,String web,String des,String address,String doj,String qual,String sal,int rate)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name", name);
initialValues.put("Phone", phone);
initialValues.put("email", web);
initialValues.put("des", des);
initialValues.put("Salary", sal);
initialValues.put("qual", qual);
initialValues.put("address", address);
initialValues.put("doj", doj);
initialValues.put("rate", rate);
return db.insert("Student", null, initialValues);
}
public boolean deleteTitle(long rowId)
{
return db.delete("Student", KEY_ID +
"=" + rowId, null) > 0;
}
public boolean UpdateTitle(long id,String name,String phone,String web,String des,String address,String doj,String qual,String sal,int rate)
{
ContentValues initialValues = new ContentValues();
initialValues.put("Name", name);
initialValues.put("Phone", phone);
initialValues.put("email", web);
initialValues.put("des", des);
initialValues.put("qual", qual);
initialValues.put("Salary", sal);
initialValues.put("address", address);
initialValues.put("doj", doj);
initialValues.put("rate", rate);
return db.update("Student",initialValues, KEY_ID + "=" + id, null)>0;
//return db.insert("Student", null, initialValues);
}
public Cursor getAllRecords()
{
return db.query("Student", new String[] {
KEY_ID,
"Name",
"Phone",
"email",
"address",
"des",
"qual",
"doj",
"Salary",
"rate"
},
null,
null,
null,
null,
null);
}
}
How exactly does __attribute__((constructor)) work?
.init
/.fini
isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init
/.fini
is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init
will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor))
. It's old-school but it has some benefits.
.ctors
/.dtors
mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor))
is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init
/.fini
instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini
).
On system supporting both methods, one possible benefit is that code in .init
is run before .ctors
and code in .fini
after .dtors
. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.
A major drawback is that you can't easily have more than one _init
and one _fini
function per each loadable module and would probably have to fragment code in more .so
than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini
default functions (provided by crti.o
). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here
Notice in the link above that a cascading to the original _init()
is not needed as it's still in place. The call
in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.
.init
/.fini
and .ctors
/.detors
mechanisms are similar, but not quite. Code in .init
/.fini
runs "as is". I.e. you can have several functions in .init
/.fini
, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so
files.
.ctors
/.dtors
are differently organized than .init
/.fini
. .ctors
/.dtors
sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.
The following snippet adds new function pointers to the .ctors
function array, principally the same way as __attribute__((constructor))
does (method can coexist with __attribute__((constructor)))
.
#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors
/.dtors
loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).
I'd prefer __attribute__((constructor))/((destructor))
where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.
Some good reference in the book Linkers & loaders.
How to call a function after a div is ready?
Thus far, the only way to "listen" on DOM events, like inserting or modifying Elements, was to use the such called Mutation Events. For instance
document.body.addEventListener('DOMNodeInserted', function( event ) {
console.log('whoot! a new Element was inserted, see my event object for details!');
}, false);
Further reading on that: MDN
The Problem with Mutation Events was (is) they never really made their way into any official spec because of inconcistencies and stuff. After a while, this events were implemented in all modern browser, but they were declared as deprecated, in other words
you don't want to use them.
The official replacement for the Mutation Events is the MutationObserver()
object.
Further reading on that: MDN
The syntax at present looks like
var observer = new MutationObserver(function( mutations ) {
mutations.forEach(function( mutation ) {
console.log( mutation.type );
});
});
var config = { childList: true };
observer.observe( document.body, config );
At this time, the API has been implemented in newer Firefox, Chrome and Safari versions. I'm not sure about IE and Opera. So the tradeoff here is definitely that you can only target for topnotch browsers.
How to build and use Google TensorFlow C++ api
I use a hack/workaround to avoid having to build the whole TF library myself (which saves both time (it's set up in 3 minutes), disk space, installing dev dependencies, and size of the resulting binary). It's officially unsupported, but works well if you just want to quickly jump in.
Install TF through pip (pip install tensorflow
or pip install tensorflow-gpu
). Then find its library _pywrap_tensorflow.so
(TF 0.* - 1.0) or _pywrap_tensorflow_internal.so
(TF 1.1+). In my case (Ubuntu) it's located at /usr/local/lib/python2.7/dist-packages/tensorflow/python/_pywrap_tensorflow.so
. Then create a symlink to this library called lib_pywrap_tensorflow.so
somewhere where your build system finds it (e.g. /usr/lib/local
). The prefix lib
is important! You can also give it another lib*.so
name - if you call it libtensorflow.so
, you may get better compatibility with other programs written to work with TF.
Then create a C++ project as you are used to (CMake, Make, Bazel, whatever you like).
And then you're ready to just link against this library to have TF available for your projects (and you also have to link against python2.7
libraries)! In CMake, you e.g. just add target_link_libraries(target _pywrap_tensorflow python2.7)
.
The C++ header files are located around this library, e.g. in /usr/local/lib/python2.7/dist-packages/tensorflow/include/
.
Once again: this way is officially unsupported and you may run in various issues. The library seems to be statically linked against e.g. protobuf, so you may run in odd link-time or run-time issues. But I am able to load a stored graph, restore the weights and run inference, which is IMO the most wanted functionality in C++.
How to change the size of the radio button using CSS?
This css seems to do the trick:
input[type=radio] {
border: 0px;
width: 100%;
height: 2em;
}
Setting the border to 0 seems to allow the user to change the size of the button and have the browser render it in that size for eg. the above height: 2em will render the button at twice the line height. This also works for checkboxes (input[type=checkbox]
). Some browsers render better than others.
From a windows box it works in IE8+, FF21+, Chrome29+.
JavaScript TypeError: Cannot read property 'style' of null
In your script, this part:
document.getElementById('Noite')
must be returning null
and you are also attempting to set the display
property to an invalid value. There are a couple of possible reasons for this first part to be null
.
You are running the script too early before the document has been loaded and thus the Noite
item can't be found.
There is no Noite
item in your HTML.
I should point out that your use of document.write()
in this case code probably signifies a problem. If the document has already loaded, then a new document.write()
will clear the old content and start a new fresh document so no Noite
item would be found.
If your document has not yet been loaded and thus you're doing document.write()
inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite
item.
The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:
document.getElementById('Noite').style.display='block';
And, make sure that there are no document.write()
statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).
In addition, setting the display
property to "display"
doesn't make sense to me. The valid options for that are "block"
, "inline"
, "none"
, "table"
, etc... I'm not aware of any option named "display"
for that style property. See here for valid options for teh display
property.
You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.
P.S. I should point out that your lack of braces for your if
statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.
I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:
- The script is located in the body, but after the content that it is referencing.
- I've added
var
declarations to your variables (a good habit to always use).
- The
if
statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
- I've added braces for every
if
statement so it absolutely clear which statements are part of the if/else
and which are not.
- I've properly closed the
</dd>
tag you were inserting.
- I've changed
style.display = '';
to style.display = 'block';
.
- I've added semicolons at the end of every statement (another good habit to follow).
The code:
<div id="Night" style="display: none;">
<img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
<img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
document.write(" Você não<br> devia<br> estar<br>dormindo?");
} else if (hr <= 11) {
document.write("Bom dia!");
} else if (hr == 12) {
document.write(" Vamos<br> almoçar?");
} else if (hr <= 17) {
document.write("Boa Tarde");
} else if (hr <= 19) {
document.write(" Bom final<br> de tarde!");
} else if (hr == 20) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
document.write(" Boa Noite");
} else if (hr == 23) {
document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>
Make Iframe to fit 100% of container's remaining height
A simple jQuery solution
Use this in a script inside the iframed page
$(function(){
if(window != top){
var autoIframeHeight = function(){
var url = location.href;
$(top.jQuery.find('iframe[src="'+ url +'"]')).css('height', $('body').height()+4);
}
$(window).on('resize',autoIframeHeight);
autoIframeHeight();
}
}
How do I compare two strings in python?
For that, you can use default difflib in python
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
then call similar() as
similar(string1, string2)
it will return compare as ,ratio >= threshold to get match result
How do you extract a column from a multi-dimensional array?
You can use this as well:
values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]
Note: This is not working for built-in array and not aligned (e.g. np.array([[1,2,3],[4,5,6,7]]) )
How to reenable event.preventDefault?
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
Get value of a merged cell of an excel from its cell address in vba
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
Traverse all the Nodes of a JSON Object Tree with JavaScript
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)
How to change the Content of a <textarea> with JavaScript
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
View/edit ID3 data for MP3 files
TagLib Sharp is pretty popular.
As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.
class MusicID3Tag
{
public byte[] TAGID = new byte[3]; // 3
public byte[] Title = new byte[30]; // 30
public byte[] Artist = new byte[30]; // 30
public byte[] Album = new byte[30]; // 30
public byte[] Year = new byte[4]; // 4
public byte[] Comment = new byte[30]; // 30
public byte[] Genre = new byte[1]; // 1
}
string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";
using (FileStream fs = File.OpenRead(filePath))
{
if (fs.Length >= 128)
{
MusicID3Tag tag = new MusicID3Tag();
fs.Seek(-128, SeekOrigin.End);
fs.Read(tag.TAGID, 0, tag.TAGID.Length);
fs.Read(tag.Title, 0, tag.Title.Length);
fs.Read(tag.Artist, 0, tag.Artist.Length);
fs.Read(tag.Album, 0, tag.Album.Length);
fs.Read(tag.Year, 0, tag.Year.Length);
fs.Read(tag.Comment, 0, tag.Comment.Length);
fs.Read(tag.Genre, 0, tag.Genre.Length);
string theTAGID = Encoding.Default.GetString(tag.TAGID);
if (theTAGID.Equals("TAG"))
{
string Title = Encoding.Default.GetString(tag.Title);
string Artist = Encoding.Default.GetString(tag.Artist);
string Album = Encoding.Default.GetString(tag.Album);
string Year = Encoding.Default.GetString(tag.Year);
string Comment = Encoding.Default.GetString(tag.Comment);
string Genre = Encoding.Default.GetString(tag.Genre);
Console.WriteLine(Title);
Console.WriteLine(Artist);
Console.WriteLine(Album);
Console.WriteLine(Year);
Console.WriteLine(Comment);
Console.WriteLine(Genre);
Console.WriteLine();
}
}
}
How to call a RESTful web service from Android?
Recently discovered that a third party library - Square Retrofit can do the job very well.
Defining REST endpoint
public interface GitHubService {
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user,Callback<List<User>> cb);
}
Getting the concrete service
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = restAdapter.create(GitHubService.class);
Calling the REST endpoint
List<Repo> repos = service.listRepos("octocat",new Callback<List<User>>() {
@Override
public void failure(final RetrofitError error) {
android.util.Log.i("example", "Error, body: " + error.getBody().toString());
}
@Override
public void success(List<User> users, Response response) {
// Do something with the List of Users object returned
// you may populate your adapter here
}
});
The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.setConverter(new GsonConverter(gson))
.build();
Add an element to an array in Swift
In Swift 4.1 and Xcode 9.4.1
We can add objects to Array basically in Two ways
let stringOne = "One"
let strigTwo = "Two"
let stringThree = "Three"
var array:[String] = []//If your array is string type
Type 1)
//To append elements at the end
array.append(stringOne)
array.append(stringThree)
Type 2)
//To add elements at specific index
array.insert(strigTwo, at: 1)
If you want to add two arrays
var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]
let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)
appending list but error 'NoneType' object has no attribute 'append'
I think what you want is this:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
Also, it looks like your statement pan_list.append(p.last)
is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
How to change string into QString?
Moreover, to convert whatever you want, you can use the QVariant class.
for example:
std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();
output
"hello !"
"10"
"5.42"
5
Nested routes with react router v4 / v5
Some thing like this.
_x000D_
_x000D_
import React from 'react';_x000D_
import {_x000D_
BrowserRouter as Router, Route, NavLink, Switch, Link_x000D_
} from 'react-router-dom';_x000D_
_x000D_
import '../assets/styles/App.css';_x000D_
_x000D_
const Home = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>HOME</h1>_x000D_
</NormalNavLinks>;_x000D_
const About = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>About</h1>_x000D_
</NormalNavLinks>;_x000D_
const Help = () =>_x000D_
<NormalNavLinks>_x000D_
<h1>Help</h1>_x000D_
</NormalNavLinks>;_x000D_
_x000D_
const AdminHome = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>root</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
const AdminAbout = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>Admin about</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
const AdminHelp = () =>_x000D_
<AdminNavLinks>_x000D_
<h1>Admin Help</h1>_x000D_
</AdminNavLinks>;_x000D_
_x000D_
_x000D_
const AdminNavLinks = (props) => (_x000D_
<div>_x000D_
<h2>Admin Menu</h2>_x000D_
<NavLink exact to="/admin">Admin Home</NavLink>_x000D_
<NavLink to="/admin/help">Admin Help</NavLink>_x000D_
<NavLink to="/admin/about">Admin About</NavLink>_x000D_
<Link to="/">Home</Link>_x000D_
{props.children}_x000D_
</div>_x000D_
);_x000D_
_x000D_
const NormalNavLinks = (props) => (_x000D_
<div>_x000D_
<h2>Normal Menu</h2>_x000D_
<NavLink exact to="/">Home</NavLink>_x000D_
<NavLink to="/help">Help</NavLink>_x000D_
<NavLink to="/about">About</NavLink>_x000D_
<Link to="/admin">Admin</Link>_x000D_
{props.children}_x000D_
</div>_x000D_
);_x000D_
_x000D_
const App = () => (_x000D_
<Router>_x000D_
<div>_x000D_
<Switch>_x000D_
<Route exact path="/" component={Home}/>_x000D_
<Route path="/help" component={Help}/>_x000D_
<Route path="/about" component={About}/>_x000D_
_x000D_
<Route exact path="/admin" component={AdminHome}/>_x000D_
<Route path="/admin/help" component={AdminHelp}/>_x000D_
<Route path="/admin/about" component={AdminAbout}/>_x000D_
</Switch>_x000D_
_x000D_
</div>_x000D_
</Router>_x000D_
);_x000D_
_x000D_
_x000D_
export default App;
_x000D_
_x000D_
_x000D_
An invalid XML character (Unicode: 0xc) was found
For people who are reading byte array into String and trying to convert to object with JAXB, you can add "iso-8859-1" encoding by creating String from byte array like this:
String JAXBallowedString= new String(byte[] input, "iso-8859-1");
This would replace the conflicting byte to single-byte encoding which JAXB can handle. Obviously this solution is only to parse the xml.
Java Error opening registry key
I followed multiple answers from above and got my issue resolved.
Issue:
Javac was on 13 from jdk but java was using 1.8 from jre so java threw incompatible runtime error
Fix:
Under Control Panel -> Programs: I uninstalled 1.8 (named Java 8 runtime) and DID NOT touch the other one (named Java (TM) SE Development Kit 13)
Deleted java.exe, javac.exe and javawc.exe files from:
a. C:\Windows\system32
b. C:\Windows\SysWOW64
c. C:\ProgramData\Oracle\Java\javapath
The environment variable JDK_HOME was pointing to 13 but JAVA_HOME was pointing to 1.8 so i pointed JAVA_HOME to also use 13 which was C:\Program Files\Java\jdk-13.0.1
There was a Path variable under both User variables and system variables sections.
For the one in user variables section, i added the string %JDK_HOME% - which translated automatically to the physical path.
For the one under system variables, I deleted the path C:\ProgramData\Oracle\Java\javapath and added C:\Program Files\Java\jdk-13.0.1\bin
All good now! Thanks to all the people who answered, you rock!
C++ getters/setters coding style
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
What is a clearfix?
If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.
It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.
display: inline-block
- Better
- Flexbox - Best (but limited browser support)
Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.
For a detailed browser list see: https://caniuse.com/flexbox.
(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)
A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.
The clearfix is a way to combat the zero-height container problem for floated elements
A clearfix is performed as follows:
.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
Or, if you don't require IE<8 support, the following is fine too:
.clearfix:after {
content: "";
display: table;
clear: both;
}
Normally you would need to do something as follows:
<div>
<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->
</div>
With clearfix, you only need the following:
<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
</div>
Read about it in this article - by Chris Coyer @ CSS-Tricks
Check synchronously if file/directory exists in Node.js
Some answers here says that fs.exists
and fs.existsSync
are both deprecated. According to the docs this is no more true. Only fs.exists
is deprected now:
Note that fs.exists() is deprecated, but fs.existsSync() is not. (The
callback parameter to fs.exists() accepts parameters that are
inconsistent with other Node.js callbacks. fs.existsSync() does not
use a callback.)
So you can safely use fs.existsSync() to synchronously check if a file exists.
How to compare strings in C conditional preprocessor-directives
You can't do that if USER is defined as a quoted string.
But you can do that if USER is just JACK or QUEEN or Joker or whatever.
There are two tricks to use:
- Token-splicing, where you combine an identifier with another identifier by just concatenating their characters. This allows you to compare against JACK without having to
#define JACK
to something
- variadic macro expansion, which allows you to handle macros with variable numbers of arguments. This allows you to expand specific identifiers into varying numbers of commas, which will become your string comparison.
So let's start out with:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
Now, if I write JACK_QUEEN_OTHER(USER)
, and USER is JACK, the preprocessor
turns that into EXPANSION1(ReSeRvEd_, JACK, 1, 2, 3)
Step two is concatenation:
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
Now JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_JACK, 1, 2, 3)
This gives the opportunity to add a number of commas according to whether or not a string matches:
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
If USER is JACK, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x,x, 1, 2, 3)
If USER is QUEEN, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(x,x, 1, 2, 3)
If USER is other, JACK_QUEEN_OTHER(USER)
becomes EXPANSION2(ReSeRvEd_other, 1, 2, 3)
At this point, something critical has happened: the fourth argument to the EXPANSION2 macro is either 1, 2, or 3, depending on whether the original argument passed was jack, queen, or anything else. So all we have to do is pick it out. For long-winded reasons, we'll need two macros for the last step; they'll be EXPANSION2 and EXPANSION3, even though one seems unnecessary.
Putting it all together, we have these 6 macros:
#define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
#define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
#define EXPANSION2(a, b, c, d, ...) EXPANSION3(a, b, c, d)
#define EXPANSION3(a, b, c, d, ...) d
#define ReSeRvEd_JACK x,x,x
#define ReSeRvEd_QUEEN x,x
And you might use them like this:
int main() {
#if JACK_QUEEN_OTHER(USER) == 1
printf("Hello, Jack!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 2
printf("Hello, Queen!\n");
#endif
#if JACK_QUEEN_OTHER(USER) == 3
printf("Hello, who are you?\n");
#endif
}
Obligatory godbolt link: https://godbolt.org/z/8WGa19
MSVC Update: You have to parenthesize slightly differently to make things also work in MSVC. The EXPANSION* macros look like this:
#define EXPANSION1(a, b, c, d, e) EXPANSION2((a##b, c, d, e))
#define EXPANSION2(x) EXPANSION3 x
#define EXPANSION3(a, b, c, d, ...) d
Obligatory: https://godbolt.org/z/96Y8a1
How to programmatically modify WCF app.config endpoint address setting?
I think what you want is to swap out at runtime a version of your config file, if so create a copy of your config file (also give it the relevant extension like .Debug or .Release) that has the correct addresses (which gives you a debug version and a runtime version ) and create a postbuild step that copies the correct file depending on the build type.
Here is an example of a postbuild event that I've used in the past which overrides the output file with the correct version (debug/runtime)
copy "$(ProjectDir)ServiceReferences.ClientConfig.$(ConfigurationName)" "$(ProjectDir)ServiceReferences.ClientConfig" /Y
where :
$(ProjectDir) is the project directory where the config files are located
$(ConfigurationName) is the active configuration build type
EDIT:
Please see Marc's answer for a detailed explanation on how to do this programmatically.
How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?
wget -r -np -nH --cut-dirs=3 -R index.html http://hostname/aaa/bbb/ccc/ddd/
From man wget
‘-r’
‘--recursive’
Turn on recursive retrieving. See Recursive Download, for more details. The default maximum depth is 5.
‘-np’
‘--no-parent’
Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded. See Directory-Based Limits, for more details.
‘-nH’
‘--no-host-directories’
Disable generation of host-prefixed directories. By default, invoking Wget with ‘-r http://fly.srk.fer.hr/’ will create a structure of directories beginning with fly.srk.fer.hr/. This option disables such behavior.
‘--cut-dirs=number’
Ignore number directory components. This is useful for getting a fine-grained control over the directory where recursive retrieval will be saved.
Take, for example, the directory at ‘ftp://ftp.xemacs.org/pub/xemacs/’. If you retrieve it with ‘-r’, it will be saved locally under ftp.xemacs.org/pub/xemacs/. While the ‘-nH’ option can remove the ftp.xemacs.org/ part, you are still stuck with pub/xemacs. This is where ‘--cut-dirs’ comes in handy; it makes Wget not “see” number remote directory components. Here are several examples of how ‘--cut-dirs’ option works.
No options -> ftp.xemacs.org/pub/xemacs/
-nH -> pub/xemacs/
-nH --cut-dirs=1 -> xemacs/
-nH --cut-dirs=2 -> .
--cut-dirs=1 -> ftp.xemacs.org/xemacs/
...
If you just want to get rid of the directory structure, this option is similar to a combination of ‘-nd’ and ‘-P’. However, unlike ‘-nd’, ‘--cut-dirs’ does not lose with subdirectories—for instance, with ‘-nH --cut-dirs=1’, a beta/ subdirectory will be placed to xemacs/beta, as one would expect.
how to git commit a whole folder?
OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.
Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.
Open your folder which you want to upload. drag and drop on the listing in browser. See the image here.
background:none vs background:transparent what is the difference?
To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent
and background-image: none
) without explicitly specifying any value such as transparent
or none
, you can do so by writing:
background: initial;
Expand Python Search Path to Other Source
The easiest way I find is to create a file "any_name.pth" and put it in your folder "\Lib\site-packages". You should find that folder wherever python is installed.
In that file, put a list of directories where you want to keep modules for importing. For instance, make a line in that file like this:
C:\Users\example...\example
You will be able to tell it works by running this in python:
import sys
for line in sys: print line
You will see your directory printed out, amongst others from where you can also import. Now you can import a "mymodule.py" file that sits in that directory as easily as:
import mymodule
This will not import subfolders. For that you could imagine creating a python script to create a .pth file containing all sub folders of a folder you define. Have it run at startup perhaps.
How to extract a substring using regex
Apache Commons Lang provides a host of helper utilities for the java.lang API, most notably String manipulation methods.
In your case, the start and end substrings are the same, so just call the following function.
StringUtils.substringBetween(String str, String tag)
Gets the String that is nested in between two instances of the same
String.
If the start and the end substrings are different then use the following overloaded method.
StringUtils.substringBetween(String str, String open, String close)
Gets the String that is nested in between two Strings.
If you want all instances of the matching substrings, then use,
StringUtils.substringsBetween(String str, String open, String close)
Searches a String for substrings delimited by a start and end tag,
returning all matching substrings in an array.
For the example in question to get all instances of the matching substring
String[] results = StringUtils.substringsBetween(mydata, "'", "'");
Nested jQuery.each() - continue/break
Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".
Typescript: How to extend two classes?
TypeScript supports decorators, and using that feature plus a little library called typescript-mix you can use mixins to have multiple inheritance with just a couple of lines
// The following line is only for intellisense to work
interface Shopperholic extends Buyer, Transportable {}
class Shopperholic {
// The following line is where we "extend" from other 2 classes
@use( Buyer, Transportable ) this
price = 2000;
}
What's the syntax to import a class in a default package in Java?
As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.
This trick doesn't work if your class is not in the default package.
Display Python datetime without time
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
How to get Toolbar from fragment?
In XML
<androidx.appcompat.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways">
</androidx.appcompat.widget.Toolbar>
Kotlin: In fragment.kt
-> onCreateView()
setHasOptionsMenu(true)
val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)
(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)
(activity as? AppCompatActivity)?.supportActionBar?.show()
-> onCreateOptionsMenu()
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.app_main_menu,menu)
super.onCreateOptionsMenu(menu, inflater)
}
->onOptionsItemSelected()
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.selected_id->{//to_do}
else -> super.onOptionsItemSelected(item)
}
}
Why do we always prefer using parameters in SQL statements?
Two years after my first go, I'm recidivating...
Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates.
Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "@myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way?
PHP errors NOT being displayed in the browser [Ubuntu 10.10]
I was just stuck on the same issue, when I've realized that I was using the open short tag form:
<? echo 'nothing will be print if no open_short_tag option is enabled'; ?>
You have to go to your /etc/apache2/php.ini
file and set the short_open_tag = Off
to On
, then sudo service apache2 restart
!
Cheers!
how to convert integer to string?
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
How to concat two ArrayLists?
add one ArrayList to second ArrayList as:
Arraylist1.addAll(Arraylist2);
EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:
ArrayList<String> arraylist3=new ArrayList<String>();
arraylist3.addAll(Arraylist1); // add first arraylist
arraylist3.addAll(Arraylist2); // add Second arraylist
Custom designing EditText
Use the below code in your rounded_edittext.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#2f6699" />
<corners
android:radius="10dp"
/>
</shape>
This should work
How to disable an Android button?
WRONG WAY IN LISTENER TO USE VARIABLE INSTEAD OF PARAMETER!!!
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
RIGHT WAY:
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/** check given view by assertion or cast as u wish */
if(v instance of Button) {
/** cast */
Button button = (Button) v;
/** we can perform some check up */
if(button.getId() == EXPECTED_ID) {
/** disable view */
button.setEnabled(false)
button.setClickable(false);
}
} else {
/** you can for example find desired view by root view */
Button bt = (Button) v.getRootView().findViewById(R.id.btId);
/*check for button */
if(bt!=null) {
/** disable button view */
...
} else {
/** according to @jeroen-bollen remark
* we made assumption that we expected a view
* of type button here in other any case
*/
throw new IllegalArgumentException("Wrong argument: " +
"View passed to method is not a Button type!");
}
}
}
});
EDIT:
In reply to @jeroen-bollen
View.OnClickListener
is Interface definition for a callback to be invoked when a view is clicked.
with method definition
void onClick(View v);
when the view is clicked the View class object makes callback to method onClick() sending as parameter itself, so null view parameter should not occur if it does it's an Assertion Error it could happen for example when View object class was destroyed in meanwhile (for example collected by GC) or method was tampered due to hack
little about instanceof & null
JLS / 15.20.2. Type Comparison Operator instanceof
At run time, the result of the instanceof operator is true
if the value of the RelationalExpression is not null
and the reference could be cast to the ReferenceType
without raising a ClassCastException.
Otherwise the result is false.
three words from the Author
IF U ASK WHY ?
MOSTLY TO AVOID NullPointerException
Little more code will save your time on later bug tracking in your code & reduces the occurrence of abnomalies.
consider following example:
View.OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)
Pandas get topmost n records within each group
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
Process all arguments except the first one (in a bash script)
Working in bash 4 or higher version:
#!/bin/bash
echo "$0"; #"bash"
bash --version; #"GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)"
In function:
echo $@; #"p1" "p2" "p3" "p4" "p5"
echo ${@: 0}; #"bash" "p1" "p2" "p3" "p4" "p5"
echo ${@: 1}; #"p1" "p2" "p3" "p4" "p5"
echo ${@: 2}; #"p2" "p3" "p4" "p5"
echo ${@: 2:1}; #"p2"
echo ${@: 2:2}; #"p2" "p3"
echo ${@: -2}; #"p4" "p5"
echo ${@: -2:1}; #"p4"
Notice the space between ':' and '-', otherwise it means different:
${var:-word} If var is null or unset,
word is substituted for var. The value of var does not change.
${var:+word} If var is set,
word is substituted for var. The value of var does not change.
Which is described in:Unix / Linux - Shell Substitution
Open fancybox from function
The answers seems a bit over complicated. I hope I didn't misunderstand the question.
If you simply want to open a fancy box from a click to an "A" tag. Just set your html to
<a id="my_fancybox" href="#contentdiv">click me</a>
The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:
$('#my_fancybox').fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
});
This will show a fancybox containing "contentdiv" when your anchor tag is clicked.
How to configure socket connect timeout
I dont program in C# but in C, we solve the same problem by making the socket non-blocking and then putting the fd in a select/poll loop with a timeout value equal to the amount of time we are willing to wait for the connect to succeed.
I found this for Visual C++ and the explanation there also bends towards the select/poll mechanism I explained before.
In my experience, you cannot change connect timeout values per socket. You change it for all (by tuning OS parameters).
Float and double datatype in Java
According to the IEEE standards, float is a 32 bit representation of a real number while double is a 64 bit representation.
In Java programs we normally mostly see the use of double data type. It's just to avoid overflows as the range of numbers that can be accommodated using the double data type is more that the range when float is used.
Also when high precision is required, the use of double is encouraged. Few library methods that were implemented a long time ago still requires the use of float data type as a must (that is only because it was implemented using float, nothing else!).
But if you are certain that your program requires small numbers and an overflow won't occur with your use of float, then the use of float will largely improve your space complexity as floats require half the memory as required by double.
Using an attribute of the current class instance as a default value for method's parameter
There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self
.
Here is an example. It is counterintuitive, but actually makes perfect sense:
def add(item, s=[]):
s.append(item)
print len(s)
add(1) # 1
add(1) # 2
add(1, []) # 1
add(1, []) # 1
add(1) # 3
This will print 1 2 1 1 3
.
Because it works the same way as
default_s=[]
def add(item, s=default_s):
s.append(item)
Obviously, if you modify default_s
, it retains these modifications.
There are various workarounds, including
def add(item, s=None):
if not s: s = []
s.append(item)
or you could do this:
def add(self, item, s=None):
if not s: s = self.makeDefaultS()
s.append(item)
Then the method makeDefaultS
will have access to self
.
Another variation:
import types
def add(item, s=lambda self:[]):
if isinstance(s, types.FunctionType): s = s("example")
s.append(item)
here the default value of s
is a factory function.
You can combine all these techniques:
class Foo:
import types
def add(self, item, s=Foo.defaultFactory):
if isinstance(s, types.FunctionType): s = s(self)
s.append(item)
def defaultFactory(self):
""" Can be overridden in a subclass, too!"""
return []
Using GregorianCalendar with SimpleDateFormat
Why such complications?
public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException
{
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
Date date = fmt.parse(dd_mm_yy);
GregorianCalendar cal = GregorianCalendar.getInstance();
cal.setTime(date);
return cal;
}
How to display Base64 images in HTML?
If you have PHP on the back-end, you can use this code:
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="'.$src.'">';
Get Environment Variable from Docker Container
One more since we are dealing with json
docker inspect <NAME|ID> | jq '.[] | .Config.Env'
Output sample
[
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"NGINX_VERSION=1.19.4",
"NJS_VERSION=0.4.4",
"PKG_RELEASE=1~buster"
]
How to enable assembly bind failure logging (Fusion) in .NET
If you have the Windows SDK installed on your machine, you'll find the "Fusion Log Viewer" under Microsoft SDK\Tools (just type "Fusion" in the start menu on Vista or Windows 7/8). Launch it, click the Settings button, and select "Log bind failure" or "Log all binds".
If these buttons are disabled, go back to the start menu, right-click the Log Viewer, and select "Run as Administrator".
Formatting a number with exactly two decimals in JavaScript
Put the following in some global scope:
Number.prototype.getDecimals = function ( decDigCount ) {
return this.toFixed(decDigCount);
}
and then try:
var a = 56.23232323;
a.getDecimals(2); // will return 56.23
Update
Note that toFixed()
can only work for the number of decimals between 0-20
i.e. a.getDecimals(25)
may generate a javascript error, so to accomodate that you may add some additional check i.e.
Number.prototype.getDecimals = function ( decDigCount ) {
return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}
"make clean" results in "No rule to make target `clean'"
This works for me. Are you sure you're indenting with tabs?
CC = gcc
CFLAGS = -g -pedantic -O0 -std=gnu99 -m32 -Wall
PROGRAMS = digitreversal
all : $(PROGRAMS)
digitreversal : digitreversal.o
[tab]$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
.PHONY: clean
clean:
[tab]@rm -f $(PROGRAMS) *.o core
How to reformat JSON in Notepad++?
Update:
As of Notepad++ v7.6, use Plugin Admin to install JSTool per this answer
INSTALL
Download it from http://sourceforge.net/projects/jsminnpp/ and copy JSMinNpp.dll to plugin directory of Notepad++. Or you can just install "JSTool" from Plugin Manager in Notepad++.
New Notepad++ install and where did PluginManager go? See How to view Plugin Manager in Notepad++
{
"menu" : {
"id" : "file",
"value" : "File",
"popup" : {
"menuitem" : [{
"value" : "New",
"onclick" : "CreateNewDoc()"
}, {
"value" : "Open",
"onclick" : "OpenDoc()"
}, {
"value" : "Close",
"onclick" : "CloseDoc()"
}
]
}
}
}
Tip: Select the code you want to reformat, then Plugins | JSTool | JSFormat.
How to store a datetime in MySQL with timezone info
You said:
I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
If this is the case, then you should not use UTC. All you need to do is to use a DATETIME
type in MySQL instead of a TIMESTAMP
type.
From the MySQL documentation:
MySQL converts TIMESTAMP
values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME
.)
If you are already using a DATETIME
type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.
Correct way of getting Client's IP Addresses from http.Request
In PHP there are a lot of variables that I should check. Is it the same on Go?
This has nothing to do with Go (or PHP for that matter). It just depends on what the client, proxy, load-balancer, or server is sending. Get the one you need depending on your environment.
http.Request.RemoteAddr
contains the remote IP address. It may or may not be your actual client.
And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))
No, why not try it yourself? http://play.golang.org/p/YMf_UBvDsH
Live Video Streaming with PHP
You can easily build a website as per the requirements. PHP will be there to handle the website development part. All the hosting and normal website development will work just as it is. However, for the streaming part, you will have to choose a good streaming service. Whether it is Red5 or Adobe, you can choose from plenty of services.
Choose a service that provides a dedicated storage to get something done right. If you do not know how to configure the server properly, you can just choose a streaming service. Good services often give a CDN that helps broadcast the stream efficiently. Simply launch your website in PHP and embed the YouTube player in the said web page to get it working.
convert UIImage to NSData
If you have an image inside a UIImageView , e.g. "myImageView", you can do the following:
Convert your image using UIImageJPEGRepresentation() or UIImagePNGRepresentation() like this:
NSData *data = UIImagePNGRepresentation(myImageView.image);
//or
NSData *data = UIImageJPEGRepresentation(myImageView.image, 0.8);
//The float param (0.8 in this example) is the compression quality
//expressed as a value from 0.0 to 1.0, where 1.0 represents
//the least compression (or best quality).
You can also put this code inside a GCD block and execute in another thread, showing an UIActivityIndicatorView during the process ...
//*code to show a loading view here*
dispatch_queue_t myQueue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{
NSData *data = UIImagePNGRepresentation(myImageView.image);
//some code....
dispatch_async( dispatch_get_main_queue(), ^{
//*code to hide the loading view here*
});
});
Filename too long in Git for Windows
You should be able to run the command
git config --system core.longpaths true
or add it to one of your Git configuration files manually to turn this functionality on, once you are on a supported version of Git. It looks like maybe 1.9.0 and after.
background: fixed no repeat not working on mobile
background-attachment:fixed
in IOS Safari has been a known bug for as long as I can recall.
Here's some other options for you:
https://stackoverflow.com/a/23420490/1004312
Since the fixed position in general is not all that stable on touch (some more than others, Chrome works great), it is still acting up in Safari IOS 8 in situations that used to work in IOS 7, therefore I generally just use JS to detect touch devices, including Windows mobile.
/* ============== SUPPORTS TOUCH OR NOT ========= */
/*! Detects touch support and adds appropriate classes to html and returns a JS object
Copyright (c) 2013 Izilla Partners Pty Ltd | http://www.izilla.com.au
Licensed under the MIT license | https://coderwall.com/p/egbgdw
*/
var supports = (function() {
var d = document.documentElement,
c = "ontouchstart" in window || navigator.msMaxTouchPoints;
if (c) {
d.className += " touch";
return {
touch: true
}
} else {
d.className += " no-touch";
return {
touch: false
}
}
})();
CSS example assumes mobile first:
.myBackgroundPrecious {
background: url(1.jpg) no-repeat center center;
background-size: cover;
}
.no-touch .myBackgroundPrecious {
background-attachment:fixed;
}
How do you kill a Thread in Java?
I'd vote for Thread.stop()
.
As for instance you have a long lasting operation (like a network request).
Supposedly you are waiting for a response, but it can take time and the user navigated to other UI.
This waiting thread is now a) useless b) potential problem because when he will get result, it's completely useless and he will trigger callbacks that can lead to number of errors.
All of that and he can do response processing that could be CPU intense. And you, as a developer, cannot even stop it, because you can't throw if (Thread.currentThread().isInterrupted())
lines in all code.
So the inability to forcefully stop a thread it weird.
What is the maximum value for an int32?
In Objective-C (iOS & OSX), just remember these macros:
#define INT8_MAX 127
#define INT16_MAX 32767
#define INT32_MAX 2147483647
#define INT64_MAX 9223372036854775807LL
#define UINT8_MAX 255
#define UINT16_MAX 65535
#define UINT32_MAX 4294967295U
#define UINT64_MAX 18446744073709551615ULL
SQL Server - Case Statement
We can use case statement Like this
select Name,EmailId,gender=case
when gender='M' then 'F'
when gender='F' then 'M'
end
from [dbo].[Employees]
WE can also it as follow.
select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
from [dbo].[Employees]
What does ON [PRIMARY] mean?
When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.
See MSDN for the full syntax.
What is the purpose of Android's <merge> tag in XML layouts?
To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/content_profile" />
</LinearLayout>
content_profile.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</LinearLayout>
In here, the entire layout file when inflated looks like this.
<LinearLayout>
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
</LinearLayout>
See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.
content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</merge>
Now our layout looks like this
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.
So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.
How to redirect to an external URL in Angular2?
None of the above solutions worked for me, I just added
window.location.href = "www.google.com"
event.preventDefault();
This worked for me.
Or try using
window.location.replace("www.google.com");
Store output of subprocess.Popen call in a string
This works perfectly for me:
import subprocess
try:
#prints results and merges stdout and std
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error and merges stdout and stderr
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output # contains stdout and stderr together
How to return an array from an AJAX call?
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
How can I pretty-print JSON using node.js?
Another workaround would be to make use of prettier to format the JSON.
The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.
const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));
CodeIgniter: 404 Page Not Found on Live Server
I was stuck with this approx a day i just rename filename "Filename" with capital letter and rename the controller class "Classname". and it solved the problem.
**class Myclass extends CI_Controller{}
save file: Myclass.php**
application/config/config.php
$config['base_url'] = '';
'Operation is not valid due to the current state of the object' error during postback
If your stack trace looks like following then you are sending a huge load of json objects to server
Operation is not valid due to the current state of the object.
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
at Failing.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something
<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>
For more details, please read this Microsoft kb article
Allowed characters in filename
You should start with the Wikipedia Filename page. It has a decent-sized table (Comparison of filename limitations), listing the reserved characters for quite a lot of file systems.
It also has a plethora of other information about each file system, including reserved file names such as CON
under MS-DOS. I mention that only because I was bitten by that once when I shortened an include file from const.h
to con.h
and spent half an hour figuring out why the compiler hung.
Turns out DOS ignored extensions for devices so that con.h
was exactly the same as con
, the input console (meaning, of course, the compiler was waiting for me to type in the header file before it would continue).
Loop in react-native
render() {
var myloop = [];
for (let i = 0; i < 10; i++) {
myloop.push(
<View key={i}>
<Text>{i}</Text>
</View>
);
}
return (
<View >
<Text >Welcome to React Native!</Text>
{myloop}
</View>
);
}
}
How to append data to a json file?
You aren't ever writing anything to do with the data you read in. Do you want to be adding the data structure in feeds to the new one you're creating?
Or perhaps you want to open the file in append mode open(filename, 'a')
and then add your string, by writing the string produced by json.dumps
instead of using json.dump
- but nneonneo points out that this would be invalid json.
jQueryUI modal dialog does not show close button (x)
Pure CSS Workaround:
I was using both bootstrap and jQuery UI and changing the order of adding the scripts broke some other objects. I ended up using pure CSS workaround:
.ui-dialog-titlebar-close {
background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_888888_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
border: medium none;
}
.ui-dialog-titlebar-close:hover {
background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_222222_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
}
Test if a string contains any of the strings from an array
A more groovyesque approach would be to use inject in combination with metaClass:
I would to love to say:
String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true
And the method would be:
myInput.metaClass.containsAny={List<String> notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
If you need containsAny to be present for any future String variable then add the method to the class instead of the object:
String.metaClass.containsAny={notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
pip: no module named _internal
I've seen this issue when PYTHONPATH
was set to include the built-in site-packages
directory. Since Python looks there automatically it is unnecessary and can be removed.
How can I increment a date by one day in Java?
In java 8 you can use java.time.LocalDate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
You can convert in into java.util.Date
object as follows.
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
You can formate LocalDate
into a String as follows.
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
"Series objects are mutable and cannot be hashed" error
gene_name = no_headers.iloc[1:,[1]]
This creates a DataFrame because you passed a list of columns (single, but still a list). When you later do this:
gene_name[x]
you now have a Series object with a single value. You can't hash the Series.
The solution is to create Series from the start.
gene_type = no_headers.iloc[1:,0]
gene_name = no_headers.iloc[1:,1]
disease_name = no_headers.iloc[1:,2]
Also, where you have orph_dict[gene_name[x]] =+ 1
, I'm guessing that's a typo and you really mean orph_dict[gene_name[x]] += 1
to increment the counter.
HTML input - name vs. id
In HTML4.01:
Name Attribute
- Valid only on
<a>
, <form>
, <iframe>
, <img>
, <map>
, <input>
, <select>
, <textarea>
- Name does not have to be unique, and can be used to group elements together such as radio buttons & checkboxes
- Can not be referenced in URL, although as JavaScript and PHP can see the URL there are workarounds
- Is referenced in JS with
getElementsByName()
- Shares the same namespace as the
id
attribute
- Must begin with a letter
- According to specs is case sensitive, but most modern browsers don't seem to follow this
- Used on form elements to submit information. Only input tags with a
name
attribute are submitted to the server
Id Attribute
- Valid on any element except
<base>
, <html>
, <head>
, <meta>
, <param>
, <script>
, <style>
, <title>
- Each Id should be unique in the page as rendered in the browser, which may or may not be all in the same file
- Can be used as anchor reference in URL
- Is referenced in CSS or URL with
#
sign
- Is referenced in JS with
getElementById()
, and jQuery by $(#<id>)
- Shares same name space as name attribute
- Must contain at least one character
- Must begin with a letter
- Must not contain anything other than letters, numbers, underscores (
_
), dashes (-
), colons (:
), or periods (.
)
- Is case insensitive
In (X)HTML5, everything is the same except:
Name Attribute
- Not valid on
<form>
anymore
- XHTML says it must be all lowercase, but most browsers don't follow that
Id Attribute
- Valid on any element
- XHTML says it must be all lowercase, but most browsers don't follow that
This question was written when HTML4.01 was the norm, and many browsers and features were different from today.
How to center cards in bootstrap 4?
You can also use Bootstrap 4 flex classes
Like: .align-item-center
and .justify-content-center
We can use these classes identically for all device view.
Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center
.text-center class is used to align text in center.
How can I set Image source with base64
Try using setAttribute
instead:
document.getElementById('img')
.setAttribute(
'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);
Real answer:
(And make sure you remove the line-breaks in the base64.)
Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files
Have you installed a different version JRE after , while using previous version of JRE in Eclipse .
if Not than :
- Right click on your project -> Build Path -> Configure Build Path
- Go to 'Libraries' tab
- Add Library -> JRE System Library -> Next -> Workspace default JRE (or you can Choose Alternate JRE form your System) -> Finish
if Yes than .
- Right click on your project -> Build Path -> Configure Build Path
- Go to 'Libraries' tab
- Remove Previous Version
- Add Library -> JRE System Library -> Next -> Workspace default JRE (or you can Choose Alternate JRE from your System) -> Finish
Can you find all classes in a package using reflection?
If you are merely looking to load a group of related classes, then Spring can help you.
Spring can instantiate a list or map of all classes that implement a given interface in one line of code. The list or map will contain instances of all the classes that implement that interface.
That being said, as an alternative to loading the list of classes out of the file system, instead just implement the same interface in all the classes you want to load, regardless of package and use Spring to provide you instances of all of them. That way, you can load (and instantiate) all the classes you desire regardless of what package they are in.
On the other hand, if having them all in a package is what you want, then simply have all the classes in that package implement a given interface.
jQuery function to get all unique elements from an array?
// for numbers
a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
$.unique(a)
[7, 6, 1, 8, 3, 2, 5, 4]
// for string
a = ["a", "a", "b"]
$.unique(a)
["b", "a"]
And for dom elements there is no example is needed here I guess because you already know that!
Here is the jsfiddle link of live example:
http://jsfiddle.net/3BtMc/4/
Is there anything like .NET's NotImplementedException in Java?
You could do it yourself (thats what I did) - in order to not be bothered with exception handling, you simply extend the RuntimeException, your class could look something like this:
public class NotImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotImplementedException(){}
}
You could extend it to take a message - but if you use the method as I do (that is, as a reminder, that there is still something to be implemented), then usually there is no need for additional messages.
I dare say, that I only use this method, while I am in the process of developing a system, makes it easier for me to not lose track of which methods are still not implemented properly :)
Pointers in Python?
Yes! there is a way to use a variable as a pointer in python!
I am sorry to say that many of answers were partially wrong. In principle every equal(=) assignation shares the memory address (check the id(obj) function), but in practice it is not such. There are variables whose equal("=") behaviour works in last term as a copy of memory space, mostly in simple objects (e.g. "int" object), and others in which not (e.g. "list","dict" objects).
Here is an example of pointer assignation
dict1 = {'first':'hello', 'second':'world'}
dict2 = dict1 # pointer assignation mechanism
dict2['first'] = 'bye'
dict1
>>> {'first':'bye', 'second':'world'}
Here is an example of copy assignation
a = 1
b = a # copy of memory mechanism. up to here id(a) == id(b)
b = 2 # new address generation. therefore without pointer behaviour
a
>>> 1
Pointer assignation is a pretty useful tool for aliasing without the waste of extra memory, in certain situations for performing comfy code,
class cls_X():
...
def method_1():
pd1 = self.obj_clsY.dict_vars_for_clsX['meth1'] # pointer dict 1: aliasing
pd1['var4'] = self.method2(pd1['var1'], pd1['var2'], pd1['var3'])
#enddef method_1
...
#endclass cls_X
but one have to be aware of this use in order to prevent code mistakes.
To conclude, by default some variables are barenames (simple objects like int, float, str,...), and some are pointers when assigned between them (e.g. dict1 = dict2). How to recognize them? just try this experiment with them. In IDEs with variable explorer panel usually appears to be the memory address ("@axbbbbbb...") in the definition of pointer-mechanism objects.
I suggest investigate in the topic. There are many people who know much more about this topic for sure. (see "ctypes" module). I hope it is helpful. Enjoy the good use of the objects! Regards, José Crespo
Simplest way to download and unzip files in Node.js cross-platform?
yauzl is a robust library for unzipping. Design principles:
- Follow the spec. Don't scan for local file headers. Read the central directory for file metadata.
- Don't block the JavaScript thread. Use and provide async APIs.
- Keep memory usage under control. Don't attempt to buffer entire files in RAM at once.
- Never crash (if used properly). Don't let malformed zip files bring down client applications who are trying to catch errors.
- Catch unsafe filenames entries. A zip file entry throws an error if its file name starts with "/" or /[A-Za-z]:// or if it contains ".." path segments or "\" (per the spec).
Currently has 97% test coverage.
Vagrant ssh authentication failure
Unable to run vagrant up because it gets stuck and times out? I recently had a "water in laptop incident" and had to migrate to a new one(on a MAC by the way). I successfully got all my projects up and running beside the one, which was using vagrant.
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
default: Adapter 2: hostonly
==> default: Forwarding ports...
default: 8000 (guest) => 8877 (host) (adapter 1)
default: 8001 (guest) => 8878 (host) (adapter 1)
default: 8080 (guest) => 7777 (host) (adapter 1)
default: 5432 (guest) => 2345 (host) (adapter 1)
default: 5000 (guest) => 8855 (host) (adapter 1)
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
It couldn't authenticate, retried again and again and eventually gave up.
This is how I got it back in shape in 3 steps:
1 - Find the IdentityFile
used by Vagrant:
$ vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/ned/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
2 - Check the public key in the IdentityFile
:
$ ssh-keygen -y -f <path-to-insecure_private_key>
It'd output something like this:
ssh-rsa AAAAB3Nyc2EAAA...9gE98OHlnVYCzRdK8jlqm8hQ==
3 - Log in to the Vagrant guest with the password vagrant
:
ssh -p 2222 -o UserKnownHostsFile=/dev/null [email protected]
The authenticity of host '[127.0.0.1]:2222 ([127.0.0.1]:2222)' can't be established.
RSA key fingerprint is dc:48:73:c3:18:e4:9d:34:a2:7d:4b:20:6a:e7:3d:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:2222' (RSA) to the list of known hosts.
[email protected]'s password: vagrant
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64)
...
NOTE: if vagrant guest is configured to disallow password authentication you need to open VBox' GUI, double click guest name, login as vagrant/vagrant
, then sudo -s
and edit /etc/ssh/sshd_config
and look for PasswordAuthentication no
line (usually at the end of the file), replace no
with yes
and restart sshd (i.e. systemctl reload sshd
or /etc/init.d/sshd restart
).
4 - Add the public key to the /home/vagrant/authorized_keys
file.
$ echo "ssh-rsa AA2EAAA...9gEdK8jlqm8hQ== vagrant" > /home/vagrant/.ssh/authorized_keys
5 - Exit (CTRL+d) and stop the Vagrant guest and then bring it back up.
IMPORTANT if you use any provisioning tools (i.e. Ansible etc) disable it before restarting your guest as Vagrant will think your guest is not provisioned because of use of insecure private key. It will reinstall the key and then run your provisioner!
$ vagrant halt
$ vagrant up
Hopefully you will have your arms in the air now...
I got this, with just a minor amend, from Ned Batchelders article - Ned you are a champ!
Excel VBA code to copy a specific string to clipboard
If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:
Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""
Checkbox Check Event Listener
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
Submit form using AJAX and jQuery
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
Why is "npm install" really slow?
One of the simple solution to speed up your npm install is to spin up a high powered machine on AWS and use that to compile your project and ship the code back to you.
I was experimenting with it and I found that there was a very high decrease in the time to run npm install. I found a tool to execute the above command easily https://stormyapp.com
Registry key Error: Java version has value '1.8', but '1.7' is required
First you should have Java 7. If you don't have, install it first (I don't know what you are using, Linux, Mac, yum, apt, homebrew, you should find out yourself.)
If you already have Java 7, run:
echo $JAVA_HOME
Output should be something like this:/usr/lib/jvm/java-8-oracle
. Near this directory, you should see java-7
directory. After you found it, run
export JAVA_HOME=${java-7-dir}
Change {java-7-dir}
with your directory path. Then you can run your command.
This is only a temporary solution. To change it permanently, put the above command to your ~/.bashrc
file.
EDIT: If you are using Windows, change environment variable of JAVA_HOME
to your Java 7 installation directory path.
jQuery checkbox onChange
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
How can I use numpy.correlate to do autocorrelation?
I'm a computational biologist, and when I had to compute the auto/cross-correlations between couples of time series of stochastic processes I realized that np.correlate
was not doing the job I needed.
Indeed, what seems to be missing from np.correlate
is the averaging over all the possible couples of time points at distance .
Here is how I defined a function doing what I needed:
def autocross(x, y):
c = np.correlate(x, y, "same")
v = [c[i]/( len(x)-abs( i - (len(x)/2) ) ) for i in range(len(c))]
return v
It seems to me none of the previous answers cover this instance of auto/cross-correlation: hope this answer may be useful to somebody working on stochastic processes like me.
Show dialog from fragment?
For me, it was the following-
MyFragment:
public class MyFragment extends Fragment implements MyDialog.Callback
{
ShowDialog activity_showDialog;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_showDialog = (ShowDialog)activity;
}
catch(ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "ShowDialog interface needs to be implemented by Activity.", e);
throw e;
}
}
@Override
public void onClick(View view)
{
...
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(this, 1); //request code
activity_showDialog.showDialog(dialog);
...
}
@Override
public void accept()
{
//accept
}
@Override
public void decline()
{
//decline
}
@Override
public void cancel()
{
//cancel
}
}
MyDialog:
public class MyDialog extends DialogFragment implements View.OnClickListener
{
private EditText mEditText;
private Button acceptButton;
private Button rejectButton;
private Button cancelButton;
public static interface Callback
{
public void accept();
public void decline();
public void cancel();
}
public MyDialog()
{
// Empty constructor required for DialogFragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.dialogfragment, container);
acceptButton = (Button) view.findViewById(R.id.dialogfragment_acceptbtn);
rejectButton = (Button) view.findViewById(R.id.dialogfragment_rejectbtn);
cancelButton = (Button) view.findViewById(R.id.dialogfragment_cancelbtn);
acceptButton.setOnClickListener(this);
rejectButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
getDialog().setTitle(R.string.dialog_title);
return view;
}
@Override
public void onClick(View v)
{
Callback callback = null;
try
{
callback = (Callback) getTargetFragment();
}
catch (ClassCastException e)
{
Log.e(this.getClass().getSimpleName(), "Callback of this class must be implemented by target fragment!", e);
throw e;
}
if (callback != null)
{
if (v == acceptButton)
{
callback.accept();
this.dismiss();
}
else if (v == rejectButton)
{
callback.decline();
this.dismiss();
}
else if (v == cancelButton)
{
callback.cancel();
this.dismiss();
}
}
}
}
Activity:
public class MyActivity extends ActionBarActivity implements ShowDialog
{
..
@Override
public void showDialog(DialogFragment dialogFragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
dialogFragment.show(fragmentManager, "dialog");
}
}
DialogFragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/dialogfragment_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="@string/example"/>
<Button
android:id="@+id/dialogfragment_acceptbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/dialogfragment_textview"
android:text="@string/accept"
/>
<Button
android:id="@+id/dialogfragment_rejectbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignLeft="@+id/dialogfragment_acceptbtn"
android:layout_below="@+id/dialogfragment_acceptbtn"
android:text="@string/decline" />
<Button
android:id="@+id/dialogfragment_cancelbtn"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_rejectbtn"
android:layout_below="@+id/dialogfragment_rejectbtn"
android:text="@string/cancel" />
<Button
android:id="@+id/dialogfragment_heightfixhiddenbtn"
android:layout_width="200dp"
android:layout_height="20dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:layout_alignLeft="@+id/dialogfragment_cancelbtn"
android:layout_below="@+id/dialogfragment_cancelbtn"
android:background="@android:color/transparent"
android:enabled="false"
android:text=" " />
</RelativeLayout>
As the name dialogfragment_heightfixhiddenbtn
shows, I just couldn't figure out a way to fix that the bottom button's height was cut in half despite saying wrap_content
, so I added a hidden button to be "cut" in half instead. Sorry for the hack.
PostgreSQL: Resetting password of PostgreSQL on Ubuntu
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
jquery $(window).height() is returning the document height
I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.
Concatenate two PySpark dataframes
I was trying to implement pandas append functionality in pyspark and what I created a custom function where we can concat 2 or more data frame even they are having different no. of columns only condition is if dataframes have identical name then their datatype should be same/match.
I have written a custom function to merge 2 dataframes.
def append_dfs(df1,df2):
list1 = df1.columns
list2 = df2.columns
for col in list2:
if(col not in list1):
df1 = df1.withColumn(col, F.lit(None))
for col in list1:
if(col not in list2):
df2 = df2.withColumn(col, F.lit(None))
return df1.unionByName(df2)
usage:
concate 2 dataframes
final_df = append_dfs(df1,df2)
-
- concate more than 2(say3) dataframes
final_df = append_dfs(append_dfs(df1,df2),df3)
example:
df1:
df2:
result=append_dfs(df1,df2)
result :
Hope this will useful.
Page redirect with successful Ajax request
Just do some error checking, and if everything passes then set window.location
to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
Checking if a file is a directory or just a file
You can call the stat() function and use the S_ISREG()
macro on the st_mode
field of the stat structure in order to determine if your path points to a regular file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.
How to define static property in TypeScript interface
The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:
interface AppPackageCheck<T> {
new (packageExists: boolean): T
checkIfPackageExists(): boolean;
}
class WebApp {
public static checkIfPackageExists(): boolean {
return false;
}
constructor(public packageExists: boolean) {}
}
class BackendApp {
constructor(public packageExists: boolean) {}
}
function createApp<T>(type: AppPackageCheck<T>): T {
const packageExists = type.checkIfPackageExists();
return new type(packageExists)
}
let web = createApp(WebApp);
// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp);
How do I set a JLabel's background color?
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
Convert np.array of type float64 to type uint8 scaling values
A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2]
, the code right now would scale that to have intensities of [0, 128, 255]
. You want these to remain small after converting to np.uint8
.
Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo
and provide it the type (dtype
) of the image and you will obtain a structure of information for that type. You would then access the max
field from this structure to determine the maximum value.
So with the above, do the following modifications to your code:
import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)
Note that I've additionally converted the image into np.float64
in case the incoming data type is not so and to maintain floating-point precision when doing the division.
Where does the .gitignore file belong?
As the other answers stated, you can place .gitignore
within any directory in a Git repository. However, if you need to have a private version of .gitignore
, you can add the rules to .git/info/exclude
file.
Python function overloading
Python 3.8 added functools.singledispatchmethod
Transform a method into a single-dispatch generic function.
To define a generic method, decorate it with the @singledispatchmethod
decorator. Note that the dispatch happens on the type of the first
non-self or non-cls argument, create your function accordingly:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(self, arg: int):
return -arg
@neg.register
def _(self, arg: bool):
return not arg
negator = Negator()
for v in [42, True, "Overloading"]:
neg = negator.neg(v)
print(f"{v=}, {neg=}")
Output
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
@singledispatchmethod supports nesting with other decorators such as
@classmethod. Note that to allow for dispatcher.register,
singledispatchmethod must be the outer most decorator. Here is the
Negator class with the neg methods being class bound:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
@staticmethod
def neg(arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(arg: int) -> int:
return -arg
@neg.register
def _(arg: bool) -> bool:
return not arg
for v in [42, True, "Overloading"]:
neg = Negator.neg(v)
print(f"{v=}, {neg=}")
Output:
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
The same pattern can be used for other similar decorators:
staticmethod, abstractmethod, and others.
What is web.xml file and what are all things can I do with it?
- No, there isn't anything that should be avoided
- The parameters related to performance are not in
web.xml
they are in the servlet container configuration files (server.xml
on tomcat)
No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):
listings
true
Draw on HTML5 Canvas using a mouse
Here's the most straightforward way to create a drawing application with canvas:
- Attach a
mousedown
, mousemove
, and mouseup
event listener to the canvas DOM
- on
mousedown
, get the mouse coordinates, and use the moveTo()
method to position your drawing cursor and the beginPath()
method to begin a new drawing path.
- on
mousemove
, continuously add a new point to the path with lineTo()
, and color the last segment with stroke()
.
- on
mouseup
, set a flag to disable the drawing.
From there, you can add all kinds of other features like giving the user the ability to choose a line thickness, color, brush strokes, and even layers.
how to find my angular version in my project?
If you try to check angular version in the browser, for me only this worked Ctrl+Shift+i and paste below command in console:
document.querySelector('[ng-version]').getAttribute('ng-version')
ex:
how to check if the input is a number or not in C?
You can use a function like strtol()
which will convert a character array to a long.
It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.
See the following program for an example:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[]) {
int i;
long val;
char *next;
// Process each argument given.
for (i = 1; i < argc; i++) {
// Get value with failure detection.
val = strtol (argv[i], &next, 10);
// Check for empty string and characters left after conversion.
if ((next == argv[i]) || (*next != '\0')) {
printf ("'%s' is not valid\n", argv[i]);
} else {
printf ("'%s' gives %ld\n", argv[i], val);
}
}
return 0;
}
Running this, you can see it in operation:
pax> testprog hello "" 42 12.2 77x
'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
Separators for Navigation
To get the separator vertically centered relative to the menu text,
.menustyle li + li:before {
content: ' | ';
padding: 0;
position: relative;
top: -2px;
}
How to add new elements to an array?
There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.
String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};
String[] array = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);
onclick go full screen
I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen
vs FullScreen
. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.
function fullScreenTgl() {
let doc=document,elm=doc.documentElement;
if (elm.requestFullscreen ) { (!doc.fullscreenElement ? elm.requestFullscreen() : doc.exitFullscreen() ) }
else if (elm.mozRequestFullScreen ) { (!doc.mozFullScreen ? elm.mozRequestFullScreen() : doc.mozCancelFullScreen() ) }
else if (elm.msRequestFullscreen ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen() : doc.msExitFullscreen() ) }
else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
else { console.log("Fullscreen support not detected."); }
}