How to get the browser viewport dimensions?
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
- gets CSS viewport
@media (width)
and @media (height)
which include scrollbars
initial-scale
and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media
values
- zoom may cause values to be 1px off due to native rounding
undefined
in IE8-
Resources
Arrow operator (->) usage in C
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than *
pointer operator.
When you are trying to access a struct's internals and you wrote it as *foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.
Thus you need to ask the compiler to first dereference whith (*foo)
and then access the member element: (*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar
which is sort of member access by pointer operator.
JQuery Find #ID, RemoveClass and AddClass
.....
$("#testID #testID2").removeClass("test2").addClass("test3");
Because you have assigned an id to img too, you can simply do this too:
$("#testID2").removeClass("test2").addClass("test3");
And finally, you can do this too:
$("#testID img").removeClass("test2").addClass("test3");
How can I save a screenshot directly to a file in Windows?
Short of installing a screen capture program, which I recommend, the best way to do this is by using the standard Print Screen method, then open Microsoft Office Picture Manager and simply paste the screenshot into the white area of the directory that you desire. It'll create a bitmap that you can edit or save-as a different format.
Calling another method java GUI
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
How to run code after some delay in Flutter?
Trigger actions after countdown
Timer(Duration(seconds: 3), () {
print("Yeah, this line is printed after 3 seconds");
});
Repeat actions
Timer.periodic(Duration(seconds: 5), (timer) {
print(DateTime.now());
});
Trigger timer immediately
Timer(Duration(seconds: 0), () {
print("Yeah, this line is printed immediately");
});
Can you have multiple $(document).ready(function(){ ... }); sections?
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func
declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Angular 2 change event - model changes
That's a known issue. Currently you have to use a workaround like shown in your question.
This is working as intended. When the change event is emitted ngModelChange
(the (...)
part of [(ngModel)]
hasn't updated the bound model yet:
<input type="checkbox" (ngModelChange)="myModel=$event" [ngModel]="mymodel">
See also
How to make a script wait for a pressed key?
If you are ok with depending on system commands you can use the following:
Linux and Mac OS X:
import os
os.system('read -s -n 1 -p "Press any key to continue..."')
print()
Windows:
import os
os.system("pause")
Find unique rows in numpy.array
We can actually turn m x n numeric numpy array into m x 1 numpy string array, please try using the following function, it provides count, inverse_idx and etc, just like numpy.unique:
import numpy as np
def uniqueRow(a):
#This function turn m x n numpy array into m x 1 numpy array storing
#string, and so the np.unique can be used
#Input: an m x n numpy array (a)
#Output unique m' x n numpy array (unique), inverse_indx, and counts
s = np.chararray((a.shape[0],1))
s[:] = '-'
b = (a).astype(np.str)
s2 = np.expand_dims(b[:,0],axis=1) + s + np.expand_dims(b[:,1],axis=1)
n = a.shape[1] - 2
for i in range(0,n):
s2 = s2 + s + np.expand_dims(b[:,i+2],axis=1)
s3, idx, inv_, c = np.unique(s2,return_index = True, return_inverse = True, return_counts = True)
return a[idx], inv_, c
Example:
A = np.array([[ 3.17 9.502 3.291],
[ 9.984 2.773 6.852],
[ 1.172 8.885 4.258],
[ 9.73 7.518 3.227],
[ 8.113 9.563 9.117],
[ 9.984 2.773 6.852],
[ 9.73 7.518 3.227]])
B, inv_, c = uniqueRow(A)
Results:
B:
[[ 1.172 8.885 4.258]
[ 3.17 9.502 3.291]
[ 8.113 9.563 9.117]
[ 9.73 7.518 3.227]
[ 9.984 2.773 6.852]]
inv_:
[3 4 1 0 2 4 0]
c:
[2 1 1 1 2]
How to check View Source in Mobile Browsers (Both Android && Feature Phone)
This is an old post but still a problem within the Chrome dev tools. I find the best way to check mobile source locally is to open the site locally in Xcode's iOS Simulator. Then from there you open the Safari browser and enable dev tools, if you have not already done this (go to preferences -> advanced -> show develop menu in menu bar). Now you will see the develop option in the main menu and can go to develop -> iOS Simulator -> and the page you have open in Xcode's iOS Simulator will be there. Once you click on it, it will open the web inspector and you can edit as you would normally in the browser dev tools.
I'm afraid this solution will only work on a Mac though as it uses Xcode.
How to subtract X days from a date using Java calendar?
Instead of writing my own addDays
as suggested by Eli, I would prefer to use DateUtils
from Apache. It is handy especially when you have to use it multiple places in your project.
The API says:
addDays(Date date, int amount)
Adds a number of days to a date returning a new object.
Note that it returns a new Date
object and does not make changes to the previous one itself.
Knockout validation
Have a look at Knockout-Validation which cleanly setups and uses what's described in the knockout documentation. Under: Live Example 1: Forcing input to be numeric
You can see it live in Fiddle
UPDATE: the fiddle has been updated to use the latest KO 2.0.3 and ko.validation 1.0.2 using the cloudfare CDN urls
To setup ko.validation:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
To setup validation rules, use extenders. For instance:
var viewModel = {
firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
lastName: ko.observable().extend({ required: true }),
emailAddress: ko.observable().extend({ // custom message
required: { message: 'Please supply your email address.' }
})
};
Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string
Your 0xED 0x6E 0x2C 0x20 bytes correspond to "ín, " in ISO-8859-1, so it looks like your content is in ISO-8859-1, not UTF-8. Tell your data provider about it and ask them to fix it, because if it doesn't work for you it probably doesn't work for other people either.
Now there are a few ways to work it around, which you should only use if you cannot load the XML normally. One of them would be to use utf8_encode()
. The downside is that if that XML contains both valid UTF-8 and some ISO-8859-1 then the result will contain mojibake. Or you can try to convert the string from UTF-8 to UTF-8 using iconv()
or mbstring, and hope they'll fix it for you. (they won't, but you can at least ignore the invalid characters so you can load your XML)
Or you can take the long, long road and validate/fix the sequences by yourself. That will take you a while depending on how familiar you are with UTF-8. Perhaps there are libraries out there that would do that, although I don't know any.
Either way, notify your data provider that they're sending invalid data so that they can fix it.
Here's a partial fix. It will definitely not fix everything, but will fix some of it. Hopefully enough for you to get by until your provider fix their stuff.
function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}
function utf8_encode_callback($m)
{
return utf8_encode($m[0]);
}
Total size of the contents of all the files in a directory
When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself.
This space is increased by a multiple of 4096 bytes as the directory grows.
du command (with or without -b option) take in count this space, as you can see typing:
mkdir test && du -b test
you will have a result of 4096 bytes for an empty dir.
So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.
If you read carefully the question, this is not what asked. The questioner asked:
the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes
that in the example above should be 20000 bytes, not 24096.
So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:
find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'
Installation Issue with matplotlib Python
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
- I assume you have installed the pip matplotlib, there is a directory in your root called
~/.matplotlib
.
- Create a file
~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
Creating new table with SELECT INTO in SQL
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
How do I vertically align something inside a span tag?
This is the simplest way to do it if you need multiple lines. Wrap you span
'd text in another span
and specify its height with line-height
. The trick to multiple lines is resetting the inner span
's line-height
.
<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
line-height: /*set height*/;
}
.textvalignmiddle > span {
display: inline-block;
vertical-align: middle;
line-height: 1em; /*set line height back to normal*/
}
DEMO
Of course the outer span
could be a div
or whathaveyou
MySQL load NULL values from CSV data
MySQL manual says:
When reading data with LOAD DATA
INFILE, empty or missing columns are
updated with ''. If you want a NULL
value in a column, you should use \N
in the data file. The literal word
“NULL” may also be used under some
circumstances.
So you need to replace the blanks with \N like this:
1,2,3,4,5
1,2,3,\N,5
1,2,3
Start thread with member function
Some users have already given their answer and explained it very well.
I would like to add few more things related to thread.
How to work with functor and thread.
Please refer to below example.
The thread will make its own copy of the object while passing the object.
#include<thread>
#include<Windows.h>
#include<iostream>
using namespace std;
class CB
{
public:
CB()
{
cout << "this=" << this << endl;
}
void operator()();
};
void CB::operator()()
{
cout << "this=" << this << endl;
for (int i = 0; i < 5; i++)
{
cout << "CB()=" << i << endl;
Sleep(1000);
}
}
void main()
{
CB obj; // please note the address of obj.
thread t(obj); // here obj will be passed by value
//i.e. thread will make it own local copy of it.
// we can confirm it by matching the address of
//object printed in the constructor
// and address of the obj printed in the function
t.join();
}
Another way of achieving the same thing is like:
void main()
{
thread t((CB()));
t.join();
}
But if you want to pass the object by reference then use the below syntax:
void main()
{
CB obj;
//thread t(obj);
thread t(std::ref(obj));
t.join();
}
Shell script to capture Process ID and kill it if exist
#!/bin/sh
#Find the Process ID for syncapp running instance
PID=`ps -ef | grep syncapp 'awk {print $2}'`
if [[ -z "$PID" ]] then
---> Kill -9 PID
fi
Not sure if this helps, but 'kill' is not spelled correctly.
It's capitalized.
Try 'kill' instead.
Removing page title and date when printing web page (with CSS?)
Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.
However, as of 2017, the @page
at-rule has been standardized, which can be used to hide the page title and date in modern browsers:
@page { size: auto; margin: 0mm; }
Print headers/footers and print margins
When printing Web documents, margins are set in the browser's Page Setup (or Print Setup) dialog box. These margin settings, although set within the browser, are controlled at the operating system/printer driver level and are not controllable at the HTML/CSS/DOM level. (For CSS-controlled printed page headers and footers see Printing Headers .)
The settings must be big enough to encompass the printer's physical non-printing areas. Further, they must be big enough to encompass the header and footer that the browser is usually configured to print (typically the page title, page number, URL and date). Note that these headers and footers, although specified by the browser and usually configurable through user preferences, are not part of the Web page itself and therefore are not controllable by CSS. In CSS terms, they fall outside the Page Box CSS2.1 Section 13.2.
... i.e. setting a margin of 0 hides the page title because the title is printed in the margin.
Credit to Vigneswaran S for this tip.
Best way to convert string to bytes in Python 3?
The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode
defaults to 'utf-8'
ever since Python 3.0. Thus the best way is
b = mystring.encode()
This will also be faster, because the default argument results not in the string "utf-8"
in the C code, but NULL
, which is much faster to check!
Here be some timings:
In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop
In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop
Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.
Using encode()
without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.
>>> 'äöä'.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Display List in a View MVC
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
python pip - install from local dir
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
Can you use @Autowired with static fields?
You can use ApplicationContextAware
@Component
public class AppContext implements ApplicationContextAware{
public static ApplicationContext applicationContext;
public AppBeans(){
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
then
static ABean bean = AppContext.applicationContext.getBean("aBean",ABean.class);
Bootstrap visible and hidden classes not working properly
Your .mobile
div has the following styles on it:
.mobile {
display: none !important;
visibility: hidden !important;
}
Therefore you need to override the visibility
property with visible
in addition to overriding the display
property with block
. Like so:
.visible-sm {
display: block !important;
visibility: visible !important;
}
Row count where data exists
Assuming that your Sheet1
is not necessary active you would need to use this improved code of yours:
i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count
Look into full worksheet reference for second argument for Range(arg1, arg2)
which important in this situation.
Load and execution sequence of a web page?
AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.
For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.
The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.
If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.
Compare a date string to datetime in SQL Server?
This function Cast(Floor(Cast(GetDate() As Float)) As DateTime) returns a datetime datatype with the time portion removed and could be used as so.
Select
*
Table1
Where
Cast(Floor(Cast(Column_DateTime As Float)) As DateTime) = '14-AUG-2008'
or
DECLARE @p_date DATETIME
SET @p_date = Cast('14 AUG 2008' as DateTime)
SELECT *
FROM table1
WHERE Cast(Floor(Cast(column_datetime As Float)) As DateTime) = @p_date
How do I scroll to an element using JavaScript?
We can implement by 3 Methods:
Note:
"automatic-scroll" => The particular element
"scrollable-div" => The scrollable area div
Method 1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
Method 2:
location.href = "#automatic-scroll";
Method 3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
Important notice: method 1 & method 2 will be useful if the scrollable area height is "auto". Method 3 is useful if we using the scrollable area height like "calc(100vh - 200px)".
How to get form input array into PHP array
However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:
<? foreach ($i = 0; $i < $total_data; $i++) : ?>
<input type="text" name="name[<?= $i ?>]" />
<input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>
Change $total_data to suit your needs. To show it, just like this:
$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);
Assuming the data was sent using POST method.
Why use armeabi-v7a code over armeabi code?
EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.
armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.
armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.
How do I create a master branch in a bare Git repository?
A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status
, etc.
If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:
# initialize your bare repo
$ git init --bare test-repo.git
# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone
# make an initial commit in the clone
$ touch README.md
$ git add .
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
* [new branch] master -> master
Maintain aspect ratio of div but fill screen width and height in CSS?
I understand that you asked that you would like a CSS
specific solution. To keep the aspect ratio, you would need to divide the height by the desired aspect ratio. 16:9 = 1.777777777778.
To get the correct height for the container, you would need to divide the current width by 1.777777777778. Since you can't check the width
of the container with just CSS
or divide by a percentage is CSS
, this is not possible without JavaScript
(to my knowledge).
I've written a working script that will keep the desired aspect ratio.
HTML
<div id="aspectRatio"></div>
CSS
body { width: 100%; height: 100%; padding: 0; margin: 0; }
#aspectRatio { background: #ff6a00; }
JavaScript
window.onload = function () {
//Let's create a function that will scale an element with the desired ratio
//Specify the element id, desired width, and height
function keepAspectRatio(id, width, height) {
var aspectRatioDiv = document.getElementById(id);
aspectRatioDiv.style.width = window.innerWidth;
aspectRatioDiv.style.height = (window.innerWidth / (width / height)) + "px";
}
//run the function when the window loads
keepAspectRatio("aspectRatio", 16, 9);
//run the function every time the window is resized
window.onresize = function (event) {
keepAspectRatio("aspectRatio", 16, 9);
}
}
You can use the function
again if you'd like to display something else with a different ratio by using
keepAspectRatio(id, width, height);
Meaning of 'const' last in a function declaration of a class?
The const
qualifier means that the methods can be called on any value of foobar
. The difference comes when you consider calling a non-const method on a const object. Consider if your foobar
type had the following extra method declaration:
class foobar {
...
const char* bar();
}
The method bar()
is non-const and can only be accessed from non-const values.
void func1(const foobar& fb1, foobar& fb2) {
const char* v1 = fb1.bar(); // won't compile
const char* v2 = fb2.bar(); // works
}
The idea behind const
though is to mark methods which will not alter the internal state of the class. This is a powerful concept but is not actually enforceable in C++. It's more of a promise than a guarantee. And one that is often broken and easily broken.
foobar& fbNonConst = const_cast<foobar&>(fb1);
How to update a pull request from forked repo?
I did it using below steps:
git reset --hard <commit key of the pull request>
- Did my changes in code I wanted to do
git add
git commit --amend
git push -f origin <name of the remote branch of pull request>
Android emulator not able to access the internet
Emulators w Android 9+ worked for me but Android 7 would not connect to the internet.
My office uses Little Snitch application firewall. I turned it off and Android 7 worked. Probably a good idea to check your firewalls.
Disabling enter key for form
Just add following code in <Head>
Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
How to output only captured groups with sed?
I believe the pattern given in the question was by way of example only, and the goal was to match any pattern.
If you have a sed with the GNU extension allowing insertion of a newline in the pattern space, one suggestion is:
> set string = "This is a sample 123 text and some 987 numbers"
>
> set pattern = "[0-9][0-9]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
123
987
> set pattern = "[a-z][a-z]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
his
is
a
sample
text
and
some
numbers
These examples are with tcsh (yes, I know its the wrong shell) with CYGWIN. (Edit: For bash, remove set, and the spaces around =.)
Using git to get just the latest revision
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Creating a fixed sidebar alongside a centered Bootstrap 3 grid
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
JSFIDDLE
What does elementFormDefault do in XSD?
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
How to add parameters to an external data query in Excel which can't be displayed graphically?
If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ?
where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.
E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.
Sub UpdateQuery
Dim cn As WorkbookConnection
Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
For Each cn In ThisWorkbook.Connections
If cn.Type = xlConnectionTypeODBC Then
Set odbcCn = cn.ODBCConnection
' If you do have multiple connections you would want to modify
' the line below each time you run through the loop.
odbcCn.CommandText = "select blah from someTable where blah like ?"
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = "select blah from someTable where blah like ?"
End If
Next
End Sub
How do I split a string so I can access item x?
This question is not about a string split approach, but about how to get the nth element.
All answers here are doing some kind of string splitting using recursion, CTE
s, multiple CHARINDEX
, REVERSE
and PATINDEX
, inventing functions, call for CLR methods, number tables, CROSS APPLY
s ... Most answers cover many lines of code.
But - if you really want nothing more than an approach to get the nth element - this can be done as real one-liner, no UDF, not even a sub-select... And as an extra benefit: type safe
Get part 2 delimited by a space:
DECLARE @input NVARCHAR(100)=N'part1 part2 part3';
SELECT CAST(N'<x>' + REPLACE(@input,N' ',N'</x><x>') + N'</x>' AS XML).value('/x[2]','nvarchar(max)')
Of course you can use variables for delimiter and position (use sql:column
to retrieve the position directly from a query's value):
DECLARE @dlmt NVARCHAR(10)=N' ';
DECLARE @pos INT = 2;
SELECT CAST(N'<x>' + REPLACE(@input,@dlmt,N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("@pos")][1]','nvarchar(max)')
If your string might include forbidden characters (especially one among &><
), you still can do it this way. Just use FOR XML PATH
on your string first to replace all forbidden characters with the fitting escape sequence implicitly.
It's a very special case if - additionally - your delimiter is the semicolon. In this case I replace the delimiter first to '#DLMT#', and replace this to the XML tags finally:
SET @input=N'Some <, > and &;Other äöü@€;One more';
SET @dlmt=N';';
SELECT CAST(N'<x>' + REPLACE((SELECT REPLACE(@input,@dlmt,'#DLMT#') AS [*] FOR XML PATH('')),N'#DLMT#',N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("@pos")][1]','nvarchar(max)');
UPDATE for SQL-Server 2016+
Regretfully the developers forgot to return the part's index with STRING_SPLIT
. But, using SQL-Server 2016+, there is JSON_VALUE
and OPENJSON
.
With JSON_VALUE
we can pass in the position as the index' array.
For OPENJSON
the documentation states clearly:
When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.
A string like 1,2,3
needs nothing more than brackets: [1,2,3]
.
A string of words like this is an example
needs to be ["this","is","an","example"]
.
These are very easy string operations. Just try it out:
DECLARE @str VARCHAR(100)='Hello John Smith';
DECLARE @position INT = 2;
--We can build the json-path '$[1]' using CONCAT
SELECT JSON_VALUE('["' + REPLACE(@str,' ','","') + '"]',CONCAT('$[',@position-1,']'));
--See this for a position safe string-splitter (zero-based):
SELECT JsonArray.[key] AS [Position]
,JsonArray.[value] AS [Part]
FROM OPENJSON('["' + REPLACE(@str,' ','","') + '"]') JsonArray
In this post I tested various approaches and found, that OPENJSON
is really fast. Even much faster than the famous "delimitedSplit8k()" method...
UPDATE 2 - Get the values type-safe
We can use an array within an array simply by using doubled [[]]
. This allows for a typed WITH
-clause:
DECLARE @SomeDelimitedString VARCHAR(100)='part1|1|20190920';
DECLARE @JsonArray NVARCHAR(MAX)=CONCAT('[["',REPLACE(@SomeDelimitedString,'|','","'),'"]]');
SELECT @SomeDelimitedString AS TheOriginal
,@JsonArray AS TransformedToJSON
,ValuesFromTheArray.*
FROM OPENJSON(@JsonArray)
WITH(TheFirstFragment VARCHAR(100) '$[0]'
,TheSecondFragment INT '$[1]'
,TheThirdFragment DATE '$[2]') ValuesFromTheArray
What are the differences between Visual Studio Code and Visual Studio?
Out of the box, Visual Studio can compile, run and debug programs.
Out of the box, Visual Studio Code can do practically nothing but open and edit text files. It can be extended to compile, run, and debug, but you will need to install other software. It's a PITA.
If you're looking for a Notepad replacement, Visual Studio Code is your man.
If you want to develop and debug code without fiddling for days with settings and installing stuff, then Visual Studio is your man.
What's the difference between Docker Compose vs. Dockerfile
The answer is neither.
Docker Compose (herein referred to as compose) will use the Dockerfile if you add the build command to your project's docker-compose.yml
.
Your Docker workflow should be to build a suitable Dockerfile
for each image you wish to create, then use compose to assemble the images using the build
command.
You can specify the path to your individual Dockerfiles using build /path/to/dockerfiles/blah
where /path/to/dockerfiles/blah
is where blah's Dockerfile
lives.
Sublime Text 2: How to delete blank/empty lines
You are looking for this:
^\n|^\s+$
it will not delete the line, if there is content with white space or tabs in front>
e.g.:
these will not be deleted:
...space... abc
...tab... abc
this will:
...space... ...nothing else...
...tab... ...nothing else...
What is the difference between sscanf or atoi to convert a string to an integer?
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
The ternary (conditional) operator in C
The ternary operator is a syntactic and readability convenience, not a performance shortcut. People are split on the merits of it for conditionals of varying complexity, but for short conditions, it can be useful to have a one-line expression.
Moreover, since it's an expression, as Charlie Martin wrote, that means it can appear on the right-hand side of a statement in C. This is valuable for being concise.
What is the convention for word separator in Java package names?
Underscores look ugly in package names. For what is worth, in case of names compound of three or more words I use initials (for example: com.company.app.ingresoegresofijo (ingreso/egreso fijo) -> com.company.app.iefijo
) and then document the package purpose in package-info.java
.
Shell script not running, command not found
Also try to dos2unix
the shell script, because sometimes it has Windows line endings and the shell does not recognize it.
$ dos2unix MigrateNshell.sh
This helps sometimes.
Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently
Arrays in JS have two types of properties:
Regular elements and associative properties (which are nothing but objects)
When you define a = new Array()
, you are defining an empty array. Note that there are no associative objects yet
When you define b = new Array(2)
, you are defining an array with two undefined locations.
In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.
console.log (a)
or console.log(b)
prints the array elements i.e. []
and [undefined, undefined]
respectively. But since a1/a2
and b1/b2
are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2)
kind of syntax
NodeJS w/Express Error: Cannot GET /
You need to define a root route.
app.get('/', function(req, res) {
// do something here.
});
Oh and you cannot specify a file within the express.static
. It needs to be a directory. The app.get('/'....
will be responsible to render that file accordingly. You can use express' render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/
folder.
Adding an onclick event to a div element
Its possible, we can specify onclick event in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>
How to pass a vector to a function?
It depends on if you want to pass the vector
as a reference or as a pointer (I am disregarding the option of passing it by value as clearly undesirable).
As a reference:
int binarySearch(int first, int last, int search4, vector<int>& random);
vector<int> random(100);
// ...
found = binarySearch(first, last, search4, random);
As a pointer:
int binarySearch(int first, int last, int search4, vector<int>* random);
vector<int> random(100);
// ...
found = binarySearch(first, last, search4, &random);
Inside binarySearch
, you will need to use .
or ->
to access the members of random
correspondingly.
Issues with your current code
binarySearch
expects a vector<int>*
, but you pass in a vector<int>
(missing a &
before random
)
- You do not dereference the pointer inside
binarySearch
before using it (for example, random[mid]
should be (*random)[mid]
- You are missing
using namespace std;
after the <include>
s
- The values you assign to
first
and last
are wrong (should be 0 and 99 instead of random[0]
and random[99]
How do I change TextView Value inside Java Code?
I presume that this question is a continuation of this one.
What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:
<TextView
android:id="@+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/rate"
/>
The string "@string/rate" refers to an entry in your strings.xml file that looks like this:
<string name="rate">Rate</string>
If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:
final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
"The new text that I'd like to display now that the user has pushed a button.");
How to convert char to integer in C?
The standard function atoi()
will likely do what you want.
A simple example using "atoi":
#include <unistd.h>
int main(int argc, char *argv[])
{
int useconds = atoi(argv[1]);
usleep(useconds);
}
Parse an URL in JavaScript
You can use a trick of creating an a
-element, add the url to it, and then use its Location object.
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
parseUrl('http://example.com/form_image_edit.php?img_id=33').search
Which will output: ?img_id=33
You could also use php.js to get the parse_url function in JavaScript.
Update (2012-07-05)
I would recommend using the excellent URI.js library if you need to do anything more than super simple URL handling.
How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
I think this actually answers your question.
It is so annoying working with date/time in javascript.
After a few gray hairs I figured out that is was actually pretty simple.
var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format
var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc = Date.UTC(str);
Here is a fiddle
Remove element of a regular array
As usual, I'm late to the party...
I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.
Reference:
http://msdn.microsoft.com/en-us/library/bb311042.aspx
So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)
using System;
namespace FunctionTesting {
// The class doesn't matter, as long as it's static
public static class SomeRandomClassWhoseNameDoesntMatter {
// Here's the actual method that extends arrays
public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
T[] nArray = new T[oArray.Length - 1];
for( int i = 0; i < nArray.Length; ++i ) {
nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
}
return nArray;
}
}
// Sample usage...
class Program {
static void Main( string[] args ) {
string[] myStrArray = { "Zero", "One", "Two", "Three" };
Console.WriteLine( String.Join( " ", myStrArray ) );
myStrArray = myStrArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myStrArray ) );
/* Output
* "Zero One Two Three"
* "Zero One Three"
*/
int[] myIntArray = { 0, 1, 2, 3 };
Console.WriteLine( String.Join( " ", myIntArray ) );
myIntArray = myIntArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myIntArray ) );
/* Output
* "0 1 2 3"
* "0 1 3"
*/
}
}
}
How to properly compare two Integers in Java?
No, == between Integer, Long etc will check for reference equality - i.e.
Integer x = ...;
Integer y = ...;
System.out.println(x == y);
this will check whether x
and y
refer to the same object rather than equal objects.
So
Integer x = new Integer(10);
Integer y = new Integer(10);
System.out.println(x == y);
is guaranteed to print false
. Interning of "small" autoboxed values can lead to tricky results:
Integer x = 10;
Integer y = 10;
System.out.println(x == y);
This will print true
, due to the rules of boxing (JLS section 5.1.7). It's still reference equality being used, but the references genuinely are equal.
If the value p being boxed is an integer literal of type int between
-128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f'
inclusive (§3.10.4), then let a and b be the results of any two boxing
conversions of p. It is always the case that a == b.
Personally I'd use:
if (x.intValue() == y.intValue())
or
if (x.equals(y))
As you say, for any comparison between a wrapper type (Integer
, Long
etc) and a numeric type (int
, long
etc) the wrapper type value is unboxed and the test is applied to the primitive values involved.
This occurs as part of binary numeric promotion (JLS section 5.6.2). Look at each individual operator's documentation to see whether it's applied. For example, from the docs for ==
and !=
(JLS 15.21.1):
If the operands of an equality
operator are both of numeric type, or
one is of numeric type and the other
is convertible (§5.1.8) to numeric
type, binary numeric promotion is
performed on the operands (§5.6.2).
and for <
, <=
, >
and >=
(JLS 15.20.1)
The type of each of the operands of a
numerical comparison operator must be
a type that is convertible (§5.1.8) to
a primitive numeric type, or a
compile-time error occurs. Binary
numeric promotion is performed on the
operands (§5.6.2). If the promoted
type of the operands is int or long,
then signed integer comparison is
performed; if this promoted type is
float or double, then floating-point
comparison is performed.
Note how none of this is considered as part of the situation where neither type is a numeric type.
How to handle screen orientation change when progress dialog and background thread active?
The original perceived problem was that the code would not survive a screen orientation change. Apparently this was "solved" by having the program handle the screen orientation change itself, instead of letting the UI framework do it (via calling onDestroy)).
I would submit that if the underlying problem is that the program will not survive onDestroy(), then the accepted solution is just a workaround that leaves the program with serious other problems and vulnerabilities. Remember that the Android framework specifically states that your activity is at risk for being destroyed almost at any time due to circumstances outside your control. Therefore, your activity must be able to survive onDestroy() and subsequent onCreate() for any reason, not just a screen orientation change.
If you are going to accept handling screen orientation changes yourself to solve the OP's problem, you need to verify that other causes of onDestroy() do not result in the same error. Are you able to do this? If not, I would question whether the "accepted" answer is really a very good one.
How do you run a single test/spec file in RSpec?
Or you can skip rake and use the 'rspec' command:
rspec path/to/spec/file.rb
In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine.
If you're using an older version of rspec it is:
spec path/to/spec/file.rb
Delete newline in Vim
J
deletes extra leading spacing (if any), joining lines with a single space. (With some exceptions: after /[.!?]$/
, two spaces may be inserted; before /^\s*)/
, no spaces are inserted.)
If you don't want that behavior, gJ
simply removes the newline and doesn't do anything clever with spaces at all.
How to restore to a different database in sql server?
For SQL Server 2012, using Sql Server Management Studio, I found these steps from the Microsoft page useful to restore to a different database file and name: (ref: http://technet.microsoft.com/en-us/library/ms175510.aspx)
Note steps 4 and 7 are important to set so as not to overwrite the existing database.
To restore a database to a new location, and optionally rename the database
- Connect to the appropriate instance of the SQL Server Database Engine, and then in Object Explorer, click the server name to expand
the server tree.
- Right-click Databases, and then click Restore Database. The Restore Database dialog box opens.
On the General page, use the Source section to specify the source and location of the backup sets to restore. Select one of the
following options:
Database
Select the database to restore from the drop-down list. The list contains only databases that have been backed up according to the
msdb backup history.
Note If the backup is taken from a different server, the destination server will not have the backup history information
for the specified database. In this case, select Device to manually
specify the file or device to restore.
Device
Click the browse (...) button to open the Select backup devices dialog box. In the Backup media type box, select one of
the listed device types. To select one or more devices for the
Backup media box, click Add. After you add the devices you want to the Backup media list box, click OK to return to the
General page. In the Source: Device: Database list box, select the name of the database which should be restored.
Note This list is only available when Device is selected. Only databases that have backups on the selected device will
be available.
- In the Destination section, the Database box is automatically populated with the name of the database to be restored.
To change the name of the database, enter the new name in the
Database box.
- In the Restore to box, leave the default as To the last backup taken or click on Timeline to access the Backup
Timeline dialog box to manually select a point in time to stop the
recovery action.
- In the Backup sets to restore grid, select the backups to restore. This grid displays the backups available for the specified
location. By default, a recovery plan is suggested. To override the
suggested recovery plan, you can change the selections in the grid.
Backups that depend on the restoration of an earlier backup are
automatically deselected when the earlier backup is deselected.
- To specify the new location of the database files, select the Files page, and then click Relocate all files to folder. Provide a new location for the Data file folder and Log file
folder. Alternatively you can keep the same folders and just rename the database and log file names.
Get month name from number
To print all months at once:
import datetime
monthint = list(range(1,13))
for X in monthint:
month = datetime.date(1900, X , 1).strftime('%B')
print(month)
Reverse the ordering of words in a string
This Question is asked in Paytm interview for Java position. I come up with the following solution.
class ReverseStringWord{
public static void main(String[] args) {
String s="My name is X Y Z";
StringBuilder result=new StringBuilder();
StringBuilder str=new StringBuilder();
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' '){
result.insert(0,str+" ");
str.setLength(0);
}
else{
str.append(s.charAt(i));
if(i==s.length()-1){
result.insert(0,str+" ");
}
}
}
System.out.println(result);
}}
Correct use for angular-translate in controllers
Actually, you should use the translate directive for such stuff instead.
<h1 translate="{{pageTitle}}"></h1>
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
However, if there's no way around and you really have to use $translate
service in the controller, you should wrap the call in a $translateChangeSuccess
event using $rootScope
in combination with $translate.instant()
like this:
.controller('foo', function ($rootScope, $scope, $translate) {
$rootScope.$on('$translateChangeSuccess', function () {
$scope.pageTitle = $translate.instant('PAGE.TITLE');
});
})
So why $rootScope
and not $scope
? The reason for that is, that in angular-translate's events are $emit
ed on $rootScope
rather than $broadcast
ed on $scope
because we don't need to broadcast through the entire scope hierarchy.
Why $translate.instant()
and not just async $translate()
? When $translateChangeSuccess
event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant()
which is synchronous and just assumes that translations are available.
Since version 2.8.0 there is also $translate.onReady()
, which returns a promise that is resolved as soon as translations are ready. See the changelog.
How to pass a list from Python, by Jinja2 to JavaScript
Make some invisible HTML tags like <label>, <p>, <input>
etc. and name its id, and the class name is a pattern so that you can retrieve it later.
Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.
_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_
Now you can retrieve the data in javascript using some javascript operation like below -
_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
_x000D_
for (var i = 0; i < total_len; i++) {_x000D_
var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
_x000D_
//Do what you need to do with tm1 and tm2._x000D_
_x000D_
console.log(tm1);_x000D_
console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_
Custom "confirm" dialog in JavaScript?
You might want to consider abstracting it out into a function like this:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
You can then use it like this:
dialog('Are you sure you want to do this?',
function() {
// Do something
},
function() {
// Do something else
}
);
Catch browser's "zoom" event in JavaScript
On iOS 10 it is possible to add an event listener to the touchmove
event and to detect, if the page is zoomed with the current event.
_x000D_
_x000D_
var prevZoomFactorX;_x000D_
var prevZoomFactorY;_x000D_
element.addEventListener("touchmove", (ev) => {_x000D_
let zoomFactorX = document.documentElement.clientWidth / window.innerWidth;_x000D_
let zoomFactorY = document.documentElement.clientHeight / window.innerHeight;_x000D_
let pageHasZoom = !(zoomFactorX === 1 && zoomFactorY === 1);_x000D_
_x000D_
if(pageHasZoom) {_x000D_
// page is zoomed_x000D_
_x000D_
if(zoomFactorX !== prevZoomFactorX || zoomFactorY !== prevZoomFactorY) {_x000D_
// page is zoomed with this event_x000D_
}_x000D_
}_x000D_
prevZoomFactorX = zoomFactorX;_x000D_
prevZoomFactorY = zoomFactorY;_x000D_
});
_x000D_
_x000D_
_x000D_
Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance
All those answers didnt help me, BUT I found another solution.
I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.
I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:
@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,
I simply removed orphanRemoval
and the update worked.
How do I run a class in a WAR from the command line?
The rules of locating classes in an archive file is that the location of the file's package declaration and the location of the file within the archive have to match. Since your class is located in WEB-INF/classes, it thinks the class is not valid to run in the current context.
The only way you can do what you're asking is to repackage the war so the .class
file resides in the mypackage
directory in the root of the archive rather than the WEB-INF/classes directory. However, if you do that you won't be able to access the file from any of your web classes anymore.
If you want to reuse this class in both the war and outside from the java command line, consider building an executable jar you can run from the command line, then putting that jar in the war
file's WEB-INF/lib directory.
javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher
The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.
In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException
exception.
If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.
In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.
Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.
What is a Data Transfer Object (DTO)?
DefN
A DTO is a hardcoded data model. It only solves the problem of modeling a data record handled by a hardcoded production process, where all fields are known at compile-time and therefore accessed via strongly typed properties.
In contrast, a dynamic model or "property bag" solves the problem of modeling a data record when the production process is created at runtime.
The Cvar
A DTO can be modeled with fields or properties, but someone invented a very useful data container called the Cvar. It is a reference to a value. When a DTO is modeled with what I call reference properties, modules can be configured to share heap memory and thereby collaboratively work on it. This completely eliminates parameter passing and O2O communication from your code. In other words, DTOs having reference properties allow code to achieve zero coupling.
class Cvar { ... }
class Cvar<T> : Cvar
{
public T Value { get; set; }
}
class MyDTO
{
public Cvar<int> X { get; set; }
public Cvar<int> Y { get; set; }
public Cvar<string> mutableString { get; set; } // >;)
}
Source: http://www.powersemantics.com/
Dynamic DTOs are a necessary component for dynamic software. To instantiate a dynamic process, one compiler step is to bind each machine in the script to the reference properties the script defines. A dynamic DTO is built by adding the Cvars to a collection.
// a dynamic DTO
class CvarRegistry : Dictionary<string, Cvar> { }
Contentions
Note: because Wix labeled the use of DTOs for organizing parameters as an "anti-pattern", I will give an authoritative opinion.
return View(model); // MVC disagrees
My collaborative architecture replaces design patterns. Refer to my web articles.
Parameters provide immediate control of a stack frame machine. If you use continuous control and therefore do not need immediate control, your modules do not need parameters. My architecture has none. In-process configuration of machines (methods) adds complexity but also value (performance) when the parameters are value types. However, reference type parameters make the consumer cause cache misses to get the values off the heap anyway -- therefore, just configure the consumer with reference properties. Fact from mechanical engineering: reliance on parameters is a kind of preoptimization, because processing (making components) itself is waste. Refer to my W article for more information. http://www.powersemantics.com/w.html.
Fowler and company might realize the benefits of DTOs outside of distributed architecture if they had ever known any other architecture. Programmers only know distributed systems. Integrated collaborative systems (aka production aka manufacturing) are something I had to claim as my own architecture, because I am the first to write code this way.
Some consider the DTO an anemic domain model, meaning it lacks functionality, but this assumes an object must own the data it interacts with. This conceptual model then forces you to deliver the data between objects, which is the model for distributed processing. However on a manufacturing line, each step can access the end product and change it without owning or controlling it. That's the difference between distributed and integrated processing. Manufacturing separates the product from operations and logistics.
There's nothing inherently wrong with modeling processing as a bunch of useless office workers who e-mail work to one another without keeping an e-mail trail, except for all the extra work and headache it creates in handling logistics and return problems. A properly modeled distributed process attaches a document (active routing) to the product describing what operations it came from and will go to. The active routing is a copy of the process source routing, which is written before the process begins. In the event of a defect or other emergency change, the active routing is modified to include the operation steps it will be sent to. This then accounts for all the labor which went into production.
C# Linq Group By on multiple columns
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
Android Notification Sound
// set notification audio (Tested upto android 10)
builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR
builder.setDefaults(Notification.DEFAULT_SOUND);
JavaScript override methods
the method modify()
that you called in the last is called in global context
if you want to override modify()
you first have to inherit A
or B
.
Maybe you're trying to do this:
In this case C
inherits A
function A() {
this.modify = function() {
alert("in A");
}
}
function B() {
this.modify = function() {
alert("in B");
}
}
C = function() {
this.modify = function() {
alert("in C");
};
C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}
C.prototype = new A();
Changing the color of a clicked table row using jQuery
To change color of a cell:
$(document).on('click', '#table tbody td', function (event) {
var selected = $(this).hasClass("obstacle");
$("#table tbody td").removeClass("obstacle");
if (!selected)
$(this).addClass("obstacle");
});
pros and cons between os.path.exists vs os.path.isdir
os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.
Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.
And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.
Sql server - log is full due to ACTIVE_TRANSACTION
Restarting the SQL Server will clear up the log space used by your database.
If this however is not an option, you can try the following:
* Issue a CHECKPOINT command to free up log space in the log file.
* Check the available log space with DBCC SQLPERF('logspace'). If only a small
percentage of your log file is actually been used, you can try a DBCC SHRINKFILE
command. This can however possibly introduce corruption in your database.
* If you have another drive with space available you can try to add a file there in
order to get enough space to attempt to resolve the issue.
Hope this will help you in finding your solution.
Iterating through a range of dates in Python
For those who are interested in Pythonic functional way:
from datetime import date, timedelta
from itertools import count, takewhile
for d in takewhile(lambda x: x<=date(2009,6,9), map(lambda x:date(2009,5,30)+timedelta(days=x), count())):
print(d)
Delete keychain items when an app is uninstalled
C# Xamarin version
const string FIRST_RUN = "hasRunBefore";
var userDefaults = NSUserDefaults.StandardUserDefaults;
if (!userDefaults.BoolForKey(FIRST_RUN))
{
//TODO: remove keychain items
userDefaults.SetBool(true, FIRST_RUN);
userDefaults.Synchronize();
}
... and to clear records from the keychain (TODO comment above)
var securityRecords = new[] { SecKind.GenericPassword,
SecKind.Certificate,
SecKind.Identity,
SecKind.InternetPassword,
SecKind.Key
};
foreach (var recordKind in securityRecords)
{
SecRecord query = new SecRecord(recordKind);
SecKeyChain.Remove(query);
}
Trim characters in Java
10 year old question but felt most of the answers were a bit convoluted or didn't quite work the way that was asked. Also the most upvoted answer here didn't provide any examples. Here's a simple class I made:
https://gist.github.com/Maxdw/d71afd11db2df4f1297ad3722d6392ec
Usage:
Trim.left("\joe\jill\", "\") == "joe\jill\"
Trim.left("jack\joe\jill\", "jack") == "\joe\jill\"
Trim.left("\\\\joe\\jill\\\\", "\") == "joe\\jill\\\\"
How to change an input button image using CSS?
Let's assume you can't change the input type, or even the src. You ONLY have css to play with.
If you know the height you want, and you have the url of a background image you want to use instead, you're in luck.
Set the height to zero and padding-top to the height you want. That'll shove the original image out of sight, giving you a perfectly clean space to show your css background-image.
Works in Chrome. No idea if it works in IE. Barely anything clever does, so probably not.
_x000D_
_x000D_
#daft {_x000D_
height: 0;_x000D_
padding-top: 100px;_x000D_
width: 100px;_x000D_
background-image: url(clever.jpg);_x000D_
}
_x000D_
<input type="image" src="daft.jpg" id="daft">
_x000D_
_x000D_
_x000D_
ipython notebook clear cell output in code
You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print(i, flush=True)
Most efficient way to prepend a value to an array
Calling unshift
only returns the length of the new array.
So, to add an element in the beginning and to return a new array, I did this:
let newVal = 'someValue';
let array = ['hello', 'world'];
[ newVal ].concat(array);
or simply with spread operator:
[ newVal, ...array ]
This way, the original array remains untouched.
ImportError: No module named 'encodings'
I was facing the same problem under Windows7. The error message looks like that:
Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'
Current thread 0x000011f4 (most recent call first):
I have installed python 2.7(uninstalled now), and I checked "Add Python to environment variables in Advanced Options" while installing python 3.6. It comes out that the Environment Variable "PYTHONHOME" and "PYTHONPATH" is still python2.7.
Finally I solved it by modify "PYTHONHOME" to python3.6 install path and remove variable "PYTHONPATH".
Why is C so fast, and why aren't other languages as fast or faster?
Back in the good ole days, there were just two types of languages: compiled and interpreted.
Compiled languages utilized a "compiler" to read the language syntax and convert it into identical assembly language code, which could than just directly on the CPU. Interpreted languages used a couple of different schemes, but essentially the language syntax was converted into an intermediate form, and then run in a "interpreter", an environment for executing the code.
Thus, in a sense, there was another "layer" -- the interpreter -- between the code and the machine. And, as always the case in a computer, more means more resources get used. Interpreters were slower, because they had to perform more operations.
More recently, we've seen more hybrid languages like Java, that employ both a compiler and an interpreter to make them work. It's complicated, but a JVM is faster, more sophisticated and way more optimized than the old interpreters, so it stands a much better change of performing (over time) closer to just straight compiled code. Of course, the newer compilers also have more fancy optimizing tricks so they tend to generate way better code than they used to as well. But most optimizations, most often (although not always) make some type of trade-off such that they are not always faster in all circumstances. Like everything else, nothing comes for free, so the optimizers must get their boast from somewhere (although often times it using compile-time CPU to save runtime CPU).
Getting back to C, it is a simple language, that can be compiled into fairly optimized assembly and then run directly on the target machine. In C, if you increment an integer, it's more than likely that it is only one assembler step in the CPU, in Java however, it could end up being a lot more than that (and could include a bit of garbage collection as well :-) C offers you an abstraction that is way closer to the machine (assembler is the closest), but you end up having to do way more work to get it going and it is not as protected, easy to use or error friendly. Most other languages give you a higher abstraction and take care of more of the underlying details for you, but in exchange for their advanced functionality they require more resources to run. As you generalize some solutions, you have to handle a broader range of computing, which often requires more resources.
Paul.
Printing prime numbers from 1 through 100
I always use this one (it's easy and fast) :
#include <iostream>
using namespace std;
int i,j;
bool b[101];
int main( )
{
for(i=2;i<101;i++){
b[i]=true;
}
for(i=1;i<101;i++){
if(b[i]){
cout<<i<<" ";
for(j=i*2;j<101;j+=i) b[j]=false;
}
}
}
Here is output of this code:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
How do I zip two arrays in JavaScript?
Use the map
method:
_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_
DEMO
Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found
As per documentation:
If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.
If you are runnning outside of Spring MVC ( Not processed by DispatchServlet) you have to use the RequestContextListener
Not just ContextLoaderListener
.
Add the following in your web.xml
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
That will provide session to Spring in order to maintain the beans in that scope
Update :
As per other answers , the @Controller
only sensible when you are with in Spring MVC Context, So the @Controller is not serving actual purpose in your code. Still you can inject your beans into any where with session scope / request scope ( you don't need Spring MVC / Controller to just inject beans in particular scope) .
Update :
RequestContextListener exposes the request to the current Thread only.
You have autowired ReportBuilder in two places
1. ReportPage
- You can see Spring injected the Report builder properly here, because we are still in Same web Thread. i did changed the order of your code to make sure the ReportBuilder injected in ReportPage like this.
log.info("ReportBuilder name: {}", reportBuilder.getName());
reportController.getReportData();
i knew the log should go after as per your logic , just for debug purpose i added .
2. UselessTasklet
- We got exception , here because this is different thread created by Spring Batch , where the Request is not exposed by RequestContextListener
.
You should have different logic to create and inject ReportBuilder
instance to Spring Batch ( May Spring Batch Parameters and using Future<ReportBuilder>
you can return for future reference)
Embed Google Map code in HTML with marker
I would suggest this way, one line iframe.
no javascript needed at all.
In query ?q=,
_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_
How is using "<%=request.getContextPath()%>" better than "../"
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed.
Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
Implementing autocomplete
I think you can use typeahead.js
. There are typescript definitions for it. so it'll be easy to use it i guess if you are using typescript for development.
Android center view in FrameLayout doesn't work
I'd suggest a RelativeLayout instead of a FrameLayout.
Assuming that you want to have the TextView always below the ImageView I'd use following layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_below="@id/imageview"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
Note that if you set the visibility
of an element to gone
then the space that element would consume is gone whereas when you use invisible
instead the space it'd consume will be preserved.
If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop
or set it to false
and on the TextView leave out the android:layout_below="@id/imageview"
attribute. Like this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_centerInParent="true"
android:src="@drawable/icon"
android:visibility="visible"/>
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="@string/hello"/>
</RelativeLayout>
I hope this is what you were looking for.
What is the difference between public, private, and protected?
Public
: is a default state when you declare a variable or method, can be accessed by anything directly to the object.
Protected
: Can be accessed only within the object and subclasses.
Private
: Can be referenced only within the object, not subclasses.
php - get numeric index of associative array
While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:
$a = array(
"nice",
"car" => "fast",
"none"
);
Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0
which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search()
searches for the index it stops at the first one because apparently ("car" == 0)
is true.
Setting array_search()
to strict mode won't solve the problem because then array_search("0", array_keys($a))
would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys()
to strings and then compares them correctly:
echo array_search("car", array_map("strval", array_keys($a)));
Prints 1
, which is correct.
EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:
$a = array(
"foo" => "bar",
"nice",
"car" => "fast",
"none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));
You will always get 0
, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:
$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));
How do you post data with a link
You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>
Just open your house.php
, find in it where you have $house = $_POST['houseVar']
and change it to:
isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']
And in the streeview.php
make links like that:
<a href="house.php?houseVar=$houseNum"></a>
Or something else. I just don't know your files and what inside it.
Command not found when using sudo
Ok this is my solution:
in ~/.bash_aliases just add the following:
# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
export PATH=$PATH:/home/your_user/bin
fi
Voila!
Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.
Notice that I need to be explicit when adding my PATH since HOME for superuser is /root
error: strcpy was not declared in this scope
Observations:
#include <cstring>
should introduce std::strcpy().
using namespace std;
(as written in medico.h) introduces any identifiers from std::
into the global namespace.
Aside from using namespace std;
being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using
in a header file (see below!), using namespace
does not affect identifiers introduced after the statement.
(using namespace std
is written in the header, which is included in medico.cpp, but #include <cstring>
comes after that.)
My advice: Put the using namespace std;
(if you insist on using it at all) into medico.cpp, after any includes, and use explicit std::
in medico.h.
strcmpi()
is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.
(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)
warning: deprecated conversion from string constant to ‘char*’
A "string constant" is when you write a string literal (e.g. "Hello"
) in your code. Its type is const char[]
, i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *
, i.e. removing the const
qualifier, generates the warning you are seeing.
OT clarification: using
in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string
and a self-written ::string
just perfectly in my code, unless I include your medico.h, because then the two classes will clash.
Don't use using
in header files.
And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.
Test if a command outputs an empty string
Here's an alternative approach that writes the std-out and std-err of some command a temporary file, and then checks to see if that file is empty. A benefit of this approach is that it captures both outputs, and does not use sub-shells or pipes. These latter aspects are important because they can interfere with trapping bash exit handling (e.g. here)
tmpfile=$(mktemp)
some-command &> "$tmpfile"
if [[ $? != 0 ]]; then
echo "Command failed"
elif [[ -s "$tmpfile" ]]; then
echo "Command generated output"
else
echo "Command has no output"
fi
rm -f "$tmpfile"
How to display Toast in Android?
Toast.makeText(app.getBaseContext(),"your string",Toast.LENGTH_SHORT).show();
instead of using "app.getBaseContext()".
You can try using "getApplicationContext()" or "getContext()".
If your code is in activity then you should use "this" of "Activty.this".
If your code is in fragment then you should go for "getActivity()"
javascript regular expression to check for IP addresses
The regex you've got already has several problems:
Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.
Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.
This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:
if(block >= 0 && block <= 255) {....}
Hope that helps.
What exactly is an instance in Java?
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()
). For example there is the class Car
, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null;
- s
is a reference, that currently references no instance, but can reference an instance of the String
class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
Get User Selected Range
This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
Sub test()
Dim myString As String
myString = Selection.Address
End Sub
How to position the div popup dialog to the center of browser screen?
Here, this ones working. :)
http://jsfiddle.net/nDNXc/1/
upd: Just in case jsfiddle is not responding here is the code...
CSS:
.holder{
width:100%;
display:block;
}
.content{
background:#fff;
padding: 28px 26px 33px 25px;
}
.popup{
border-radius: 7px;
background:#6b6a63;
margin:30px auto 0;
padding:6px;
// here it comes
position:absolute;
width:800px;
top: 50%;
left: 50%;
margin-left: -400px; // 1/2 width
margin-top: -40px; // 1/2 height
}
HTML:
<div class="holder">
<div id="popup" class="popup">
<div class="content">some lengthy text</div>
</div>
</div>
how to use LIKE with column name
declare @LkeVal as Varchar(100)
declare @LkeSelect Varchar(100)
Set @LkeSelect = (select top 1 <column> from <table> where <column> = 'value')
Set @LkeVal = '%' + @LkeSelect
select * from <table2> where <column2> like(''+@LkeVal+'');
How to get a complete list of object's methods and attributes?
Only to supplement:
dir()
is the most powerful/fundamental tool. (Most recommended)
Solutions other than dir()
merely provide their way of dealing the output of dir()
.
Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __
, but sometimes you may well need the __doc__
doc-string.
__dir__()
and dir()
returns identical content.
__dict__
and dir()
are different. __dict__
returns incomplete content.
IMPORTANT: __dir__()
can be sometimes overwritten with a function, value or type, by the author for whatever purpose.
Here is an example:
\\...\\torchfun.py in traverse(self, mod, search_attributes)
445 if prefix in traversed_mod_names:
446 continue
447 names = dir(m)
448 for name in names:
449 obj = getattr(m,name)
TypeError: descriptor __dir__
of 'object'
object needs an argument
The author of PyTorch modified the __dir__()
method to something that requires an argument. This modification makes dir()
fail.
If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
@Controller
public class CustomerController{
@Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
How to make android listview scrollable?
Putting ListView
inside a ScrollView
is never inspired.
But if you want your posted XML-like behavior, there're 3 options to me:
Remove ScrollView
: Removing your ScrollView
, you may give the ListView
s some specific size with respect to the total layout (either specific dp
or layout_weight
).
Replace ListView
s with LinearLayout
s: You may add the list-items by iterating through the item-list and add each item-view to the respective LinearLayout
by inflating the view & setting the respective data (string, image etc.)
If you really need to put your ListView
s inside the ScrollView
, you must make your ListView
s non-scrollable (Which is practically the same as the solution 2 above, but with ListView
codes), otherwise the layout won't function as you expect.
To make a ListView
non-scrollable, you may read this SO post, where the precise solution to me is like the one below:
_x000D_
_x000D_
listView.setOnTouchListener(new OnTouchListener() {_x000D_
public boolean onTouch(View v, MotionEvent event) {_x000D_
return (event.getAction() == MotionEvent.ACTION_MOVE);_x000D_
}_x000D_
});
_x000D_
_x000D_
_x000D_
How to upload files on server folder using jsp
public class FileUploadExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
How to terminate process from Python using pid?
So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.
It also answers the question in a way(even though it is an old one with lots of answers).
While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!
import pandas as pd
import wmi
from re import escape
import os
def kill_process(kill_path, execs):
f = wmi.WMI()
esc = escape(kill_path)
temp = {'id':[], 'path':[], 'name':[]}
for process in f.Win32_Process():
temp['id'].append(process.ProcessId)
temp['path'].append(process.ExecutablePath)
temp['name'].append(process.Name)
temp = pd.DataFrame(temp)
temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
[os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]
PostgreSQL 'NOT IN' and subquery
You could also use a LEFT JOIN and IS NULL condition:
SELECT
mac,
creation_date
FROM
logs
LEFT JOIN consols ON logs.mac = consols.mac
WHERE
logs_type_id=11
AND
consols.mac IS NULL;
An index on the "mac" columns might improve performance.
proper way to logout from a session in PHP
Personally, I do the following:
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy
).
Combine two pandas Data Frames (join on a common column)
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
OS X Terminal UTF-8 issues
Try
- Having a Powerline compatible font installed https://github.com/powerline/fonts
- Setting these ENV vars in
.zshrc
or .bashrc
:
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
CONVERT Image url to Base64
imageToBase64 = (URL) => {
let image;
image = new Image();
image.crossOrigin = 'Anonymous';
image.addEventListener('load', function() {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);
try {
localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
} catch (err) {
console.error(err)
}
});
image.src = URL;
};
imageToBase64('image URL')
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
How to disable a particular checkstyle rule for a particular line of code?
If you prefer to use annotations to selectively silence rules, this is now possible using the @SuppressWarnings
annotation, starting with Checkstyle 5.7 (and supported by the Checkstyle Maven Plugin 2.12+).
First, in your checkstyle.xml
, add the SuppressWarningsHolder
module to the TreeWalker
:
<module name="TreeWalker">
<!-- Make the @SuppressWarnings annotations available to Checkstyle -->
<module name="SuppressWarningsHolder" />
</module>
Next, enable the SuppressWarningsFilter
there (as a sibling to TreeWalker
):
<!-- Filter out Checkstyle warnings that have been suppressed with the @SuppressWarnings annotation -->
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
...
Now you can annotate e.g. the method you want to exclude from a certain Checkstyle rule:
@SuppressWarnings("checkstyle:methodlength")
@Override
public boolean equals(Object obj) {
// very long auto-generated equals() method
}
The checkstyle:
prefix in the argument to @SuppressWarnings
is optional, but I like it as a reminder where this warning came from. The rule name must be lowercase.
Lastly, if you're using Eclipse, it will complain about the argument being unknown to it:
Unsupported @SuppressWarnings("checkstyle:methodlength")
You can disable this Eclipse warning in the preferences if you like:
Preferences:
Java
--> Compiler
--> Errors/Warnings
--> Annotations
--> Unhandled token in '@SuppressWarnings': set to 'Ignore'
#if DEBUG vs. Conditional("DEBUG")
It really depends on what you're going for:
#if DEBUG
: The code in here won't even reach the IL on release.
[Conditional("DEBUG")]
: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.
Personally I use both depending on the situation:
Conditional("DEBUG") Example: I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.
[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
GetType(), propertyName));
}
You really don't want to create a function using #if DEBUG
unless you are willing to wrap every call to that function with the same #if DEBUG
:
#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething(); //This works, but looks FUGLY
#endif
}
versus:
[Conditional("DEBUG")]
public void DoSomething() { }
public void Foo()
{
DoSomething(); //Code compiles and is cleaner, DoSomething always
//exists, however this is only called during DEBUG.
}
#if DEBUG example: I use this when trying to setup different bindings for WCF communication.
#if DEBUG
public const String ENDPOINT = "Localhost";
#else
public const String ENDPOINT = "BasicHttpBinding";
#endif
In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.
Update: I am updating this answer to clarify an important and tricky point. If you choose to use the ConditionalAttribute
, keep in mind that calls are omitted during compilation, and not runtime. That is:
MyLibrary.dll
[Conditional("DEBUG")]
public void A()
{
Console.WriteLine("A");
B();
}
[Conditional("DEBUG")]
public void B()
{
Console.WriteLine("B");
}
When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to B()
from within A()
omitted, even if a call to A()
is included because DEBUG is defined in the calling assembly.
Angularjs error Unknown provider
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
Smooth scrolling when clicking an anchor link
There are already a lot of good answers here - however they are all missing the fact that empty anchors have to be excluded. Otherwise those scripts generate JavaScript errors as soon as an empty anchor is clicked.
In my opinion the correct answer is like this:
$('a[href*=\\#]:not([href$=\\#])').click(function() {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
how do I initialize a float to its max/min value?
There's no real need to initialize to smallest/largest possible to find the smallest/largest in the array:
double largest = smallest = array[0];
for (int i=1; i<array_size; i++) {
if (array[i] < smallest)
smallest = array[i];
if (array[i] > largest0
largest= array[i];
}
Or, if you're doing it more than once:
#include <utility>
template <class iter>
std::pair<typename iter::value_type, typename iter::value_type> find_extrema(iter begin, iter end) {
std::pair<typename iter::value_type, typename iter::value_type> ret;
ret.first = ret.second = *begin;
while (++begin != end) {
if (*begin < ret.first)
ret.first = *begin;
if (*begin > ret.second)
ret.second = *begin;
}
return ret;
}
The disadvantage of providing sample code -- I see others have already suggested the same idea.
Note that while the standard has a min_element and max_element, using these would require scanning through the data twice, which could be a problem if the array is large at all. Recent standards have addressed this by adding a std::minmax_element
, which does the same as the find_extrema
above (find both the minimum and maximum elements in a collection in a single pass).
Edit: Addressing the problem of finding the smallest non-zero value in an array of unsigned: observe that unsigned values "wrap around" when they reach an extreme. To find the smallest non-zero value, we can subtract one from each for the comparison. Any zero values will "wrap around" to the largest possible value for the type, but the relationship between other values will be retained. After we're done, we obviously add one back to the value we found.
unsigned int min_nonzero(std::vector<unsigned int> const &values) {
if (vector.size() == 0)
return 0;
unsigned int temp = values[0]-1;
for (int i=1; i<values.size(); i++)
if (values[i]-1 < temp)
temp = values[i]-1;
return temp+1;
}
Note this still uses the first element for the initial value, but we still don't need any "special case" code -- since that will wrap around to the largest possible value, any non-zero value will compare as being smaller. The result will be the smallest nonzero value, or 0 if and only if the vector contained no non-zero values.
Android Activity as a dialog
To start activity as dialog I defined it like this in AndroidManifest.xml
:
<activity android:theme="@android:style/Theme.Dialog" />
Use this property inside your activity
tag to avoid that your Dialog appears in the recently used apps list
android:excludeFromRecents="true"
If you want to stop your dialog / activity from being destroyed when the user clicks outside of the dialog:
After setContentView()
in your Activity
use:
this.setFinishOnTouchOutside(false);
Now when I call startActivity()
it displays as a dialog, with the previous activity shown when the user presses the back button.
Note that if you are using ActionBarActivity
(or AppCompat theme), you'll need to use @style/Theme.AppCompat.Dialog
instead.
Error Dropping Database (Can't rmdir '.test\', errno: 17)
Anybody coming from Manjaro/Arch, installing XAMPP with PHP8 and then downgrading to 7.4 will get this error. To fix, simply go to /opt/lampp/var/mysql/ with Thunar as root user, and delete the database file with the same database name in question and database should be gone. You can get the database name with PhpMyAdmin.
What is the best way to redirect a page using React Router?
One of the simplest way: use Link as follows:
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
If we want to cover the whole div section as link:
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
SQL JOIN - WHERE clause vs. ON clause
for better performance tables should have a special indexed column to use for JOINS .
so if the column you condition on is not one of those indexed columns then i suspect it is better to keep it in WHERE .
so you JOIN using the indexed columns, then after JOIN you run the condition on the none indexed column .
Plotting in a non-blocking way with Matplotlib
Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot
command that was not there when I was just doing show
:
MatplotlibDeprecationWarning: Adding an axes using the same arguments
as a previous axes currently reuses the earlier instance. In a future
version, a new instance will always be created and returned.
Meanwhile, this warning can be suppressed, and the future behavior
ensured, by passing a unique label to each axes instance.
In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.
Here's the code that worked for me:
def plt_show():
'''Text-blocking version of plt.show()
Use this instead of plt.show()'''
plt.draw()
plt.pause(0.001)
input("Press enter to continue...")
plt.close()
Pip Install not installing into correct directory?
This is what worked for me on Windows. The cause being multiple python installations
- update path with correct python
- uninstall pip using
python -m pip uninstall pip setuptools
- restart windows didn't work until a restart
Simple 3x3 matrix inverse code (C++)
A rather nice (I think) header file containing macros for most 2x2, 3x3 and 4x4 matrix operations has been available with most OpenGL toolkits. Not as standard but I've seen it at various places.
You can check it out here. At the end of it you will find both inverse of 2x2, 3x3 and 4x4.
vvector.h
When is TCP option SO_LINGER (0) required?
In servers, you may like to send RST
instead of FIN
when disconnecting misbehaving clients. That skips FIN-WAIT
followed by TIME-WAIT
socket states in the server, which prevents from depleting server resources, and, hence, protects from this kind of denial-of-service attack.
Smooth scroll to specific div on click
There are many examples of smooth scrolling using JS libraries like jQuery, Mootools, Prototype, etc.
The following example is on pure JavaScript. If you have no jQuery/Mootools/Prototype on page or you don't want to overload page with heavy JS libraries the example will be of help.
http://jsfiddle.net/rjSfP/
HTML Part:
<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>
CSS Part:
.first {
width: 100%;
height: 1000px;
background: #ccc;
}
.second {
width: 100%;
height: 1000px;
background: #999;
}
JS Part:
window.smoothScroll = function(target) {
var scrollContainer = target;
do { //find scroll container
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do { //find the top of target relatively to the container
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
scroll = function(c, a, b, i) {
i++; if (i > 30) return;
c.scrollTop = a + (b - a) / 30 * i;
setTimeout(function(){ scroll(c, a, b, i); }, 20);
}
// start scrolling
scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}
How to make a UILabel clickable?
For swift 3.0 You can also change gesture long press time duration
label.isUserInteractionEnabled = true
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:)))
longPress.minimumPressDuration = 0.2
label.addGestureRecognizer(longPress)
Regular expressions inside SQL Server
Try this
select * from mytable
where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'
Of course, you'll need to adjust the substring value, but the rest should work...
Difference between Activity Context and Application Context
This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext
or Activity
directly, instead of using parent class Context.
In the second place, the doc should specify which context to use or not explicitly.
Is there a conditional ternary operator in VB.NET?
If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"
For example, if your not careful you may be tempted to try something like:
Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
Will give "foo" a value of 0!
I think the '?' operator equivalent in C# would instead fail compilation
If my interface must return Task what is the best way to have a no-operation implementation?
Task.Delay(0)
as in the accepted answer was a good approach, as it is a cached copy of a completed Task
.
As of 4.6 there's now Task.CompletedTask
which is more explicit in its purpose, but not only does Task.Delay(0)
still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask
.
The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0)
was better than the accepted answer.
excel formula to subtract number of days from a date
Here is what worked for me (Excel 14.0 - aka MS Office Pro Plus 2010):
=DATE(YEAR(A1), MONTH(A1), DAY(A1) - 16)
This takes the date (format mm/dd/yyyy) in cell A1 and subtracts 16 days with output in format of mm/dd/yyyy.
Convert Java Date to UTC String
java.time.Instant
Just use Instant
of java.time
.
System.out.println(Instant.now());
This just printed:
2018-01-27T09:35:23.179612Z
Instant.toString
always gives UTC time.
The output is usually sortable, but there are unfortunate exceptions. toString
gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now()
seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).
Instant
is one of the classes in java.time
, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date
class. java.time
is built into Java 8 and later and has also been backported to Java 6 and 7.
Git branching: master vs. origin/master vs. remotes/origin/master
One clarification (and a point that confused me):
"remotes/origin/HEAD is the default branch" is not really correct.
remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.
Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.
browser sessionStorage. share between tabs?
You can just use localStorage
and remember the date it was first created in session cookie
. When localStorage
"session" is older than the value of cookie then you may clear the localStorage
Cons of this is that someone can still read the data after the browser is closed so it's not a good solution if your data is private and confidental.
You can store your data to localStorage
for a couple of seconds and add event listener for a storage
event. This way you will know when any of the tabs wrote something to the localStorage
and you can copy its content to the sessionStorage
, then just clear the localStorage
Display the binary representation of a number in C?
Use a lookup table, like:
char *table[16] = {"0000", "0001", .... "1111"};
then print each nibble like this
printf("%s%s", table[a / 0x10], table[a % 0x10]);
Surely you can use just one table, but it will be marginally faster and too big.