Convert web page to image
I'm not sure if this is quite what you're looking for but I've had a lot of success
using an HTML to Postscript converter html2ps to create postscript copies
of web pages, which I then convert to .gif or .pngs
This doesn't produce exact screenshot quality that you'd get from a web browser
and doesn't handle complicated things like flash or css all that well, but the advantage
is that you can run it on the web server.
(I use it to create thumbnails of user created content, for navigation)
CSS Background image not loading
I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:
apps/assets/stylesheets/main.scss
I wanted to render background image in header tag. The following was my original implementation.
header {
text-align: center;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('../images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:
ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)
I tried different variations of the url:
url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK
and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:
url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED
I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...
header {
text-align: center;
height: 390px;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.
It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.
How can I output a UTF-8 CSV in PHP that Excel will read properly?
EASY solution for Mac Excel 2008:
I struggled with this soo many times, but here was my easy fix:
Open the .csv file in Textwrangler which should open your UTF-8 chars correctly. Now in the bottom status bar change the file format from "Unicode (UTF-8)" to "Western (ISO Latin 1)" and save the file.
Now go to your Mac Excel 2008 and select File > Import > Select csv > Find your file > in File origin select "Windows (ANSI)" and voila the UTF-8 chars are showing correctly. At least it does for me...
Add CSS class to a div in code behind
Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.
public static void RemoveCssClass(this WebControl control, String css) {
control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl control, String css) {
control.RemoveCssClass(css);
css += " " + control.CssClass;
control.CssClass = css;
}
Usage: hlCreateNew.AddCssClass("disabled");
Usage: hlCreateNew.RemoveCssClass("disabled");
When should we use mutex and when should we use semaphore
Mutex is to protect the shared resource.
Semaphore is to dispatch the threads.
Mutex:
Imagine that there are some tickets to sell. We can simulate a case where many people buy the tickets at the same time: each person is a thread to buy tickets. Obviously we need to use the mutex to protect the tickets because it is the shared resource.
Semaphore:
Imagine that we need to do a calculation as below:
c = a + b;
Also, we need a function geta()
to calculate a
, a function getb()
to calculate b
and a function getc()
to do the calculation c = a + b
.
Obviously, we can't do the c = a + b
unless geta()
and getb()
have been finished.
If the three functions are three threads, we need to dispatch the three threads.
int a, b, c;
void geta()
{
a = calculatea();
semaphore_increase();
}
void getb()
{
b = calculateb();
semaphore_increase();
}
void getc()
{
semaphore_decrease();
semaphore_decrease();
c = a + b;
}
t1 = thread_create(geta);
t2 = thread_create(getb);
t3 = thread_create(getc);
thread_join(t3);
With the help of the semaphore, the code above can make sure that t3
won't do its job untill t1
and t2
have done their jobs.
In a word, semaphore is to make threads execute as a logicial order whereas mutex is to protect shared resource.
So they are NOT the same thing even if some people always say that mutex is a special semaphore with the initial value 1. You can say like this too but please notice that they are used in different cases. Don't replace one by the other even if you can do that.
How to uninstall a package installed with pip install --user
Having tested this using Python 3.5 and pip 7.1.2 on Linux, the situation appears to be this:
pip install --user somepackage
installs to $HOME/.local
, and uninstalling it does work using pip uninstall somepackage
.
This is true whether or not somepackage
is also installed system-wide at the same time.
If the package is installed at both places, only the local one will be uninstalled. To uninstall the package system-wide using pip
, first uninstall it locally, then run the same uninstall command again, with root
privileges.
In addition to the predefined user install directory, pip install --target somedir somepackage
will install the package into somedir
. There is no way to uninstall a package from such a place using pip
. (But there is a somewhat old unmerged pull request on Github that implements pip uninstall --target
.)
Since the only places pip
will ever uninstall from are system-wide and predefined user-local, you need to run pip uninstall
as the respective user to uninstall from a given user's local install directory.
Autoincrement VersionCode with gradle extra properties
in the Gradle 5.1.1 version on mac ive changed how the task names got retrieved, i althought tried to get build flavour / type from build but was to lazy to split the task name:
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def value = 0
def runTasks = gradle.getStartParameter().getTaskRequests().toString()
if (runTasks.contains('assemble') || runTasks.contains('assembleRelease') || runTasks.contains('aR')) {
value = 1
}
def versionMajor = 1
def versionMinor = 0
def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value
versionProps['VERSION_PATCH'] = versionPatch.toString()
versionProps['VERSION_BUILD'] = versionBuild.toString()
versionProps['VERSION_NUMBER'] = versionNumber.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
applicationId "de.evomotion.ms10"
minSdkVersion 21
targetSdkVersion 28
versionCode versionNumber
versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild})"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
signingConfig signingConfigs.debug
}
} else {
throw new GradleException("Could not read version.properties!")
}
code is from @just_user
this one
Jenkins, specifying JAVA_HOME
In Ubuntu 12.04 I had to install
openjdk-7-jdk
then javac was working !
then I could use
/usr/lib/jvm/java-7-openjdk-amd64
as path and jenkins didn't complain anymore.
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)
You will get this error when you call any of the setXxx()
methods on PreparedStatement
, while the SQL query string does not have any placeholders ?
for this.
For example this is wrong:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
You need to fix the SQL query string accordingly to specify the placeholders.
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
Note the parameter index starts with 1
and that you do not need to quote those placeholders like so:
String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.
See also:
How do I use itertools.groupby()?
This basic implementation helped me understand this function. Hope it helps others as well:
arr = [(1, "A"), (1, "B"), (1, "C"), (2, "D"), (2, "E"), (3, "F")]
for k,g in groupby(arr, lambda x: x[0]):
print("--", k, "--")
for tup in g:
print(tup[1]) # tup[0] == k
-- 1 --
A
B
C
-- 2 --
D
E
-- 3 --
F
Jquery UI tooltip does not support html content
You can also achieve this completely without jQueryUI by using CSS styles. See the snippet below:
_x000D_
_x000D_
div#Tooltip_Text_container {_x000D_
max-width: 25em;_x000D_
height: auto;_x000D_
display: inline;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
cursor: default;_x000D_
font-weight: normal;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container a span.tooltips {_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
transition: visibility 0s linear 0.2s, opacity 0.2s linear;_x000D_
position: absolute;_x000D_
left: 10px;_x000D_
top: 18px;_x000D_
width: 30em;_x000D_
border: 1px solid #404040;_x000D_
padding: 0.2em 0.5em;_x000D_
cursor: default;_x000D_
line-height: 140%;_x000D_
font-size: 12px;_x000D_
font-family: 'Segoe UI';_x000D_
-moz-border-radius: 3px;_x000D_
-webkit-border-radius: 3px;_x000D_
border-radius: 3px;_x000D_
-moz-box-shadow: 7px 7px 5px -5px #666;_x000D_
-webkit-box-shadow: 7px 7px 5px -5px #666;_x000D_
box-shadow: 7px 7px 5px -5px #666;_x000D_
background: #E4E5F0 repeat-x;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container:hover a span.tooltips {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
transition-delay: 0.2s;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container img {_x000D_
left: -10px;_x000D_
}_x000D_
_x000D_
div#Tooltip_Text_container:hover a span.tooltips {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
transition-delay: 0.2s;_x000D_
}
_x000D_
<div id="Tooltip_Text_container">_x000D_
<span><b>Tooltip headline</b></span>_x000D_
<a href="#">_x000D_
<span class="tooltips">_x000D_
<b>This is </b> a tooltip<br/>_x000D_
<b>This is </b> another tooltip<br/>_x000D_
</span>_x000D_
</a>_x000D_
<br/>Move the mousepointer to the tooltip headline above. _x000D_
</div>
_x000D_
_x000D_
_x000D_
The first span is for the displayed text, the second span for the hidden text, which is shown when you hover over it.
Can you use CSS to mirror/flip text?
There's also the rotateY
for a real mirror one:
transform: rotateY(180deg);
Which, perhaps, is even more clear and understandable.
EDIT: Doesn't seem to work on Opera though… sadly. But it works fine on Firefox. I guess it might required to implicitly say that we are doing some kind of translate3d
perhaps? Or something like that.
Appending pandas dataframes generated in a for loop
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
Magento - Retrieve products with a specific attribute value
To Get TEXT
attributes added from admin to front end on product listing page.
Thanks Anita Mourya
I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.
METHOD 1
on list.phtml
<?php $i=0; foreach ($_productCollection as $_product): ?>
FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH
<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>
<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>
METHOD 2
Mage/Catalog/Block/Product/List.phtml
OVER RIDE and set in 'local folder'
i.e.
Copy From
Mage/Catalog/Block/Product/List.phtml
and PASTE TO
app/code/local/Mage/Catalog/Block/Product/List.phtml
change the function by adding 2 lines shown in bold below.
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = Mage::getSingleton('catalog/layer');
/* @var $layer Mage_Catalog_Model_Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
}
// if this is a product view page
if (Mage::registry('product')) {
// get collection of categories this product is associated with
$categories = Mage::registry('product')->getCategoryCollection()
->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator()));
}
}
$origCategory = null;
if ($this->getCategoryId()) {
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
if ($category->getId()) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$this->_productCollection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
}
**//CMI-PK added na_author to filter on product listing page//
$this->_productCollection->addAttributeToSelect('na_author');**
return $this->_productCollection;
}
and you will be happy to see it....!!
Is it possible to install iOS 6 SDK on Xcode 5?
Find and download old SDK. Older SDKs are found here.
I have copied the xcode.app directory as Xcode_4.6.3.app.
Now you can test and debug in both xcode versions. You have to run them from the corresponding folders or create shortcuts in your desktop. When building from command line give the parameter as iPhoneOS6.1
instead of iPhoneOS7.0
This worked great for me in Xcode5 and iOS.
Go to into Xcode5's SDK dir. Its usually located at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Add a symbolic link to the old SDK like this:
sudo ln -s /Applications/Xcode_4.6.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk iPhoneOS6.1.sdk
Or more accurately from anywhere in the command line,
sudo ln -s /Applications/Xcode_4.6.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk
How can I set the form action through JavaScript?
Plain JavaScript:
document.getElementById('form_id').action; //Will retrieve it
document.getElementById('form_id').action = "script.php"; //Will set it
Using jQuery...
$("#form_id").attr("action"); //Will retrieve it
$("#form_id").attr("action", "/script.php"); //Will set it
Read input from a JOptionPane.showInputDialog box
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
How to use the read command in Bash?
The read
in your script command is fine. However, you execute it in the pipeline, which means it is in a subshell, therefore, the variables it reads to are not visible in the parent shell. You can either
move the rest of the script in the subshell, too:
echo hello | { read str
echo $str
}
or use command substitution to get the value of the variable out of the subshell
str=$(echo hello)
echo $str
or a slightly more complicated example (Grabbing the 2nd element of ls)
str=$(ls | { read a; read a; echo $a; })
echo $str
Batch files: List all files in a directory with relative paths
Of course, you may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
set mypath=
call :treeProcess
goto :eof
:treeProcess
setlocal
for %%f in (*.txt) do echo %mypath%%%f
for /D %%d in (*) do (
set mypath=%mypath%%%d\
cd %%d
call :treeProcess
cd ..
)
endlocal
exit /b
How to execute Table valued function
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
When to use 'npm start' and when to use 'ng serve'?
Best answer is great, short and on point, but I would like to put my pennyworth.
Basically npm start and ng serve can be used interchangeably in Angular projects as long as you do not want the command to do additional stuff. Let me elaborate on this one.
For example you may want to configure your proxy in package.json start script like this: "start": "ng serve --proxy-config proxy.config.json",
Obviously sole use of ng serve will not be enough.
Another instance is when instead of using the defaults you need to use some additional options ad hoc like define the temporary port: ng serve --port 4444
Some parameters are only available to ng serve, others to npm start. Notice that port option works for both, so in that case it is up to your taste, again. :)
How to use a link to call JavaScript?
Or, if you're using PrototypeJS
<script type="text/javascript>
Event.observe( $('thelink'), 'click', function(event) {
//do stuff
Event.stop(event);
}
</script>
<a href="#" id="thelink">This is the link</a>
socket.error: [Errno 48] Address already in use
You can also serve on the next-highest available port doing something like this in Python:
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
port = 8000
while True:
try:
httpd = SocketServer.TCPServer(('', port), Handler)
print 'Serving on port', port
httpd.serve_forever()
except SocketServer.socket.error as exc:
if exc.args[0] != 48:
raise
print 'Port', port, 'already in use'
port += 1
else:
break
If you need to do the same thing for other utilities, it may be more convenient as a bash script:
#!/usr/bin/env bash
MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}
(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1
Set that up as a executable with the name get-free-port
and you can do something like this:
someprogram --port=$(get-free-port)
That's not as reliable as the native Python approach because the bash script doesn't capture the port -- another process could grab the port before your process does (race condition) -- but still may be useful enough when using a utility that doesn't have a try-try-again approach of its own.
Android Location Providers - GPS or Network Provider?
There are some great answers mentioned here. Another approach you could take would be to use some free SDKs available online like Atooma, tranql and Neura, that can be integrated with your Android application (it takes less than 20 min to integrate).
Along with giving you the accurate location of your user, it can also give you good insights about your user’s activities. Also, some of them consume less than 1% of your battery
print call stack in C or C++
Of course the next question is: will this be enough ?
The main disadvantage of stack-traces is that why you have the precise function being called you do not have anything else, like the value of its arguments, which is very useful for debugging.
If you have access to gcc and gdb, I would suggest using assert
to check for a specific condition, and produce a memory dump if it is not met. Of course this means the process will stop, but you'll have a full fledged report instead of a mere stack-trace.
If you wish for a less obtrusive way, you can always use logging. There are very efficient logging facilities out there, like Pantheios for example. Which once again could give you a much more accurate image of what is going on.
Guzzle 6: no more json() method for responses
$response
is instance of PSR-7 ResponseInterface
. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces
getBody()
returns StreamInterface
:
/**
* Gets the body of the message.
*
* @return StreamInterface Returns the body as a stream.
*/
public function getBody();
StreamInterface
implements __toString()
which does
Reads all data from the stream into a string, from the beginning to end.
Therefore, to read body as string, you have to cast it to string:
$stringBody = (string) $response->getBody()
Gotchas
json_decode($response->getBody()
is not the best solution as it magically casts stream into string for you. json_decode()
requires string as 1st argument.
- Don't use
$response->getBody()->getContents()
unless you know what you're doing. If you read documentation for getContents()
, it says: Returns the remaining contents in a string
. Therefore, calling getContents()
reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.
Remove a cookie
You have to delete cookies with php in your server and also with js for your browser.. (They has made with php, but cookie files are in the browser client too):
An example:
if ($_GET['action'] == 'exit'){
// delete cookies with js and then in server with php:
echo '
<script type="text/javascript">
var delete_cookie = function(name) {
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
};
delete_cookie("madw");
delete_cookie("usdw");
</script>
';
unset($_COOKIE['cookie_name']);
unset($_COOKIE['cookie_time']);
How to remove blank lines from a Unix file
grep . file
grep looks at your file line-by-line; the dot .
matches anything except a newline character. The output from grep is therefore all the lines that consist of something other than a single newline.
KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element
You should never apply bindings more than once to a view. In 2.2, the behaviour was undefined, but still unsupported. In 2.3, it now correctly shows an error. When using knockout, the goal is to apply bindings once to your view(s) on the page, then use changes to observables on your viewmodel to change the appearance and behaviour of your view(s) on your page.
how to display employee names starting with a and then b in sql
To get employee names starting with A or B listed in order...
select employee_name
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name
If you are using Microsoft SQL Server you could use
....
where employee_name LIKE '[A-B]%'
order by employee_name
This is not standard SQL though it just gets translated to the following which is.
WHERE employee_name >= 'A'
AND employee_name < 'C'
For all variants you would need to consider whether you want to include accented variants such as Á
and test whether the queries above do what you want with these on your RDBMS and collation options.
The application has stopped unexpectedly: How to Debug?
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
Calculate distance between two latitude-longitude points? (Haversine formula)
I needed to calculate a lot of distances between the points for my project, so I went ahead and tried to optimize the code, I have found here. On average in different browsers my new implementation runs 2 times faster than the most upvoted answer.
function distance(lat1, lon1, lat2, lon2) {
var p = 0.017453292519943295; // Math.PI / 180
var c = Math.cos;
var a = 0.5 - c((lat2 - lat1) * p)/2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p))/2;
return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
}
You can play with my jsPerf and see the results here.
Recently I needed to do the same in python, so here is a python implementation:
from math import cos, asin, sqrt, pi
def distance(lat1, lon1, lat2, lon2):
p = pi/180
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
return 12742 * asin(sqrt(a)) #2*R*asin...
And for the sake of completeness: Haversine on wiki.
Check if list<t> contains any of another list
If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:
var items = (from x in parameters
join y in myStrings on x.Source equals y
select x)
.ToList();
How can I write to the console in PHP?
function phpconsole($label='var', $x) {
?>
<script type="text/javascript">
console.log('<?php echo ($label)?>');
console.log('<?php echo json_encode($x)?>');
</script>
<?php
}
is there a require for json in node.js
A nifty non-caching async one liner for node 15 modules:
import { readFile } from 'fs/promises';
const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);
ASP.NET MVC Ajax Error handling
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
What is the difference between . (dot) and $ (dollar sign)?
($)
allows functions to be chained together without adding parentheses to control evaluation order:
Prelude> head (tail "asdf")
's'
Prelude> head $ tail "asdf"
's'
The compose operator (.)
creates a new function without specifying the arguments:
Prelude> let second x = head $ tail x
Prelude> second "asdf"
's'
Prelude> let second = head . tail
Prelude> second "asdf"
's'
The example above is arguably illustrative, but doesn't really show the convenience of using composition. Here's another analogy:
Prelude> let third x = head $ tail $ tail x
Prelude> map third ["asdf", "qwer", "1234"]
"de3"
If we only use third once, we can avoid naming it by using a lambda:
Prelude> map (\x -> head $ tail $ tail x) ["asdf", "qwer", "1234"]
"de3"
Finally, composition lets us avoid the lambda:
Prelude> map (head . tail . tail) ["asdf", "qwer", "1234"]
"de3"
How to kill a thread instantly in C#?
You can kill instantly doing it in that way:
private Thread _myThread = new Thread(SomeThreadMethod);
private void SomeThreadMethod()
{
// do whatever you want
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
_myThread.Abort();
}
I always use it and works for me:)
Hide div by default and show it on click with bootstrap
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
- You need to make sure the target
div
has an ID.
- Bootstrap has a
class
"collapse", this will hide your block by
default. If you want your div to be collapsible AND be shown by
default you need to add "in" class to the collapse. Otherwise the
toggle behavior will not work properly.
- Then, on your hyperlink (also works for buttons), add an href
attribute that points to your target div.
- Finally, add the attribute
data-toggle="collapse"
to instruct
Bootstrap to add an appropriate toggle script to this tag.
Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
How to add button inside input
This can be achieved using inline-block
JS fiddle here
<html>
<body class="body">
<div class="form">
<form class="email-form">
<input type="text" class="input">
<a href="#" class="button">Button</a>
</form>
</div>
</body>
</html>
<style>
* {
box-sizing: border-box;
}
.body {
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
.form {
display: block;
margin: 0 0 15px;
}
.email-form {
display: block;
margin-top: 20px;
margin-left: 20px;
}
.button {
height: 40px;
display: inline-block;
padding: 9px 15px;
background-color: grey;
color: white;
border: 0;
line-height: inherit;
text-decoration: none;
cursor: pointer;
}
.input {
display: inline-block;
width: 200px;
height: 40px;
margin-bottom: 0px;
padding: 9px 12px;
color: #333333;
vertical-align: middle;
background-color: #ffffff;
border: 1px solid #cccccc;
margin: 0;
line-height: 1.42857143;
}
</style>
How to zoom in/out an UIImage object when user pinches screen?
As others described, the easiest solution is to put your UIImageView into a UIScrollView. I did this in the Interface Builder .xib file.
In viewDidLoad, set the following variables. Set your controller to be a UIScrollViewDelegate.
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView.minimumZoomScale = 0.5;
self.scrollView.maximumZoomScale = 6.0;
self.scrollView.contentSize = self.imageView.frame.size;
self.scrollView.delegate = self;
}
You are required to implement the following method to return the imageView you want to zoom.
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
In versions prior to iOS9, you may also need to add this empty delegate method:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
}
The Apple Documentation does a good job of describing how to do this:
Count how many files in directory PHP
The best answer in my opinion:
$num = count(glob("/exact/path/to/files/" . "*"));
echo $num;
- It doesnt counts . and ..
- Its a one liner
- Im proud of it
Mac OS X - EnvironmentError: mysql_config not found
Ok, well, first of all, let me check if I am on the same page as you:
- You installed python
- You did
brew install mysql
- You did
export PATH=$PATH:/usr/local/mysql/bin
- And finally, you did
pip install MySQL-Python
(or pip3 install mysqlclient
if using python 3)
If you did all those steps in the same order, and you still got an error, read on to the end, if, however, you did not follow these exact steps try, following them from the very beginning.
So, you followed the steps, and you're still geting an error, well, there are a few things you could try:
Try running which mysql_config
from bash. It probably won't be found. That's why the build isn't finding it either. Try running locate mysql_config
and see if anything comes back. The path to this binary needs to be either in your shell's $PATH environment variable, or it needs to be explicitly in the setup.py file for the module assuming it's looking in some specific place for that file.
Instead of using MySQL-Python, try using 'mysql-connector-python', it can be installed using pip install mysql-connector-python
. More information on this can be found here and here.
Manually find the location of 'mysql/bin', 'mysql_config', and 'MySQL-Python', and add all these to the $PATH environment variable.
If all above steps fail, then you could try installing 'mysql' using MacPorts, in which case the file 'mysql_config' would actually be called 'mysql_config5', and in this case, you would have to do this after installing: export PATH=$PATH:/opt/local/lib/mysql5/bin
. You can find more details here.
Note1: I've seen some people saying that installing python-dev
and libmysqlclient-dev
also helped, however I do not know if these packages are available on Mac OS.
Note2: Also, make sure to try running the commands as root.
I got my answers from (besides my brain) these places (maybe you could have a look at them, to see if it would help): 1, 2, 3, 4.
I hoped I helped, and would be happy to know if any of this worked, or not. Good luck.
How to filter object array based on attributes?
I use my ruleOut
function for filtering objects based on specific unwanted property values. I understand that in your example you would like to use conditions instead of values, but my answer is valid for the question title, so I'd like to leave my method here.
function ruleOut(arr, filterObj, applyAllFilters=true) {
return arr.filter( row => {
for (var field in filterObj) {
var val = row[field];
if (val) {
if (applyAllFilters && filterObj[field].indexOf(val) > -1) return false;
else if (!applyAllFilters) {
return filterObj[field].filter(function(filterValue){
return (val.indexOf(filterValue)>-1);
}).length == 0;
}
}
}
return true;
});
}
Say you have a list of actors like this:
let actors = [
{userName:"Mary", job:"star", language:"Turkish"},
{userName:"John", job:"actor", language:"Turkish"},
{userName:"Takis", job:"star", language:"Greek"},
{userName:"Joe", job:"star", language:"Turkish"},
{userName:"Bill", job:"star", language:"Turkish"}
];
and you would like to find all actors that are rated as Holywood stars, their nationality should not be one of 'English', 'Italian', 'Spanish', 'Greek', plus their name would not be one of 'Mary', 'Joe'. Bizzar example, I know! Anyway, with that set of conditions you would create the following object:
let unwantedFieldsFilter= {
userName: ['Mary', 'Joe'],
job: ['actor'],
language: ['English', 'Italian', 'Spanish', 'Greek']
};
OK, now if you ruleOut(actors, unwantedFieldsFilter)
you would only get
[{userName: "Bill", job: "star", language: "Turkish"}]
And Bill is your man, since his name is not one of 'Mary', 'Joe', his nationality is not included in ['English', 'Italian', 'Spanish', 'Greek'] plus he is a Star!
There is one option in my method, that is applyAllFilters
and is true by default.
If you would try to ruleOut with this param set as false, that would work as an 'OR' filtering instead of 'AND'.
Example: ruleOut(actors, {job:["actor"], language:["Italian"]}, false)
would get you everyone that is not an actor or Italian:
[{userName: "Mary", job: "star", language: "Turkish"},
{userName: "Takis", job: "star", language: "Greek"},
{userName: "Joe", job: "star", language: "Turkish"},
{userName: "Bill", job: "star", language: "Turkish"}]
Remove unused imports in Android Studio
Since Android Studio 3+, this can be done by open the option "Optimize imports".
Alt+Enter the select "Optimize imports".
This must be enough to removed the unused imports.
plot is not defined
If you want to use a function form a package or module in python you have to import and reference them.
For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
How to do while loops with multiple conditions
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
How to change port for jenkins window service when 8080 is being used
For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.
e.g. map docker container internal jenkins GUI port 8080 to port 9090 external
docker run -it -d --name jenkins42 --restart always \
-p <ip>:9090:8080 <image>
What are the basic rules and idioms for operator overloading?
Common operators to overload
Most of the work in overloading operators is boiler-plate code. That is little wonder, since operators are merely syntactic sugar, their actual work could be done by (and often is forwarded to) plain functions. But it is important that you get this boiler-plate code right. If you fail, either your operator’s code won’t compile or your users’ code won’t compile or your users’ code will behave surprisingly.
Assignment Operator
There's a lot to be said about assignment. However, most of it has already been said in GMan's famous Copy-And-Swap FAQ, so I'll skip most of it here, only listing the perfect assignment operator for reference:
X& X::operator=(X rhs)
{
swap(rhs);
return *this;
}
Bitshift Operators (used for Stream I/O)
The bitshift operators <<
and >>
, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications. For guidance overloading as bit-manipulation operators, see the section below on Binary Arithmetic Operators. For implementing your own custom format and parsing logic when your object is used with iostreams, continue.
The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax specifies no restriction on whether they should be members or non-members.
Since they change their left argument (they alter the stream’s state), they should, according to the rules of thumb, be implemented as members of their left operand’s type. However, their left operands are streams from the standard library, and while most of the stream output and input operators defined by the standard library are indeed defined as members of the stream classes, when you implement output and input operations for your own types, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions.
The canonical forms of the two are these:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
std::istream& operator>>(std::istream& is, T& obj)
{
// read obj from stream
if( /* no valid object of T found in stream */ )
is.setstate(std::ios::failbit);
return is;
}
When implementing operator>>
, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.
Function call operator
The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit this
argument of member functions. Other than this, it can be overloaded to take any number of additional arguments, including zero.
Here's an example of the syntax:
class foo {
public:
// Overloaded call operator
int operator()(const std::string& y) {
// ...
}
};
Usage:
foo f;
int a = f("hello");
Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.
Comparison operators
The binary infix comparison operators should, according to the rules of thumb, be implemented as non-member functions1. The unary prefix negation !
should (according to the same rules) be implemented as a member function. (but it is usually not a good idea to overload it.)
The standard library’s algorithms (e.g. std::sort()
) and types (e.g. std::map
) will always only expect operator<
to be present. However, the users of your type will expect all the other operators to be present, too, so if you define operator<
, be sure to follow the third fundamental rule of operator overloading and also define all the other boolean comparison operators. The canonical way to implement them is this:
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}
The important thing to note here is that only two of these operators actually do anything, the others are just forwarding their arguments to either of these two to do the actual work.
The syntax for overloading the remaining binary boolean operators (||
, &&
) follows the rules of the comparison operators. However, it is very unlikely that you would find a reasonable use case for these2.
1 As with all rules of thumb, sometimes there might be reasons to break this one, too. If so, do not forget that the left-hand operand of the binary comparison operators, which for member functions will be *this
, needs to be const
, too. So a comparison operator implemented as a member function would have to have this signature:
bool operator<(const X& rhs) const { /* do actual comparison with *this */ }
(Note the const
at the end.)
2 It should be noted that the built-in version of ||
and &&
use shortcut semantics. While the user defined ones (because they are syntactic sugar for method calls) do not use shortcut semantics. User will expect these operators to have shortcut semantics, and their code may depend on it, Therefore it is highly advised NEVER to define them.
Arithmetic Operators
Unary arithmetic operators
The unary increment and decrement operators come in both prefix and postfix flavor. To tell one from the other, the postfix variants take an additional dummy int argument. If you overload increment or decrement, be sure to always implement both prefix and postfix versions.
Here is the canonical implementation of increment, decrement follows the same rules:
class X {
X& operator++()
{
// do actual increment
return *this;
}
X operator++(int)
{
X tmp(*this);
operator++();
return tmp;
}
};
Note that the postfix variant is implemented in terms of prefix. Also note that postfix does an extra copy.2
Overloading unary minus and plus is not very common and probably best avoided. If needed, they should probably be overloaded as member functions.
2 Also note that the postfix variant does more work and is therefore less efficient to use than the prefix variant. This is a good reason to generally prefer prefix increment over postfix increment. While compilers can usually optimize away the additional work of postfix increment for built-in types, they might not be able to do the same for user-defined types (which could be something as innocently looking as a list iterator). Once you got used to do i++
, it becomes very hard to remember to do ++i
instead when i
is not of a built-in type (plus you'd have to change code when changing a type), so it is better to make a habit of always using prefix increment, unless postfix is explicitly needed.
Binary arithmetic operators
For the binary arithmetic operators, do not forget to obey the third basic rule operator overloading: If you provide +
, also provide +=
, if you provide -
, do not omit -=
, etc. Andrew Koenig is said to have been the first to observe that the compound assignment operators can be used as a base for their non-compound counterparts. That is, operator +
is implemented in terms of +=
, -
is implemented in terms of -=
etc.
According to our rules of thumb, +
and its companions should be non-members, while their compound assignment counterparts (+=
etc.), changing their left argument, should be a member. Here is the exemplary code for +=
and +
; the other binary arithmetic operators should be implemented in the same way:
class X {
X& operator+=(const X& rhs)
{
// actual addition of rhs to *this
return *this;
}
};
inline X operator+(X lhs, const X& rhs)
{
lhs += rhs;
return lhs;
}
operator+=
returns its result per reference, while operator+
returns a copy of its result. Of course, returning a reference is usually more efficient than returning a copy, but in the case of operator+
, there is no way around the copying. When you write a + b
, you expect the result to be a new value, which is why operator+
has to return a new value.3
Also note that operator+
takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator=
taking its argument per copy.
The bit manipulation operators ~
&
|
^
<<
>>
should be implemented in the same way as the arithmetic operators. However, (except for overloading <<
and >>
for output and input) there are very few reasonable use cases for overloading these.
3 Again, the lesson to be taken from this is that a += b
is, in general, more efficient than a + b
and should be preferred if possible.
Array Subscripting
The array subscript operator is a binary operator which must be implemented as a class member. It is used for container-like types that allow access to their data elements by a key.
The canonical form of providing these is this:
class X {
value_type& operator[](index_type idx);
const value_type& operator[](index_type idx) const;
// ...
};
Unless you do not want users of your class to be able to change data elements returned by operator[]
(in which case you can omit the non-const variant), you should always provide both variants of the operator.
If value_type is known to refer to a built-in type, the const variant of the operator should better return a copy instead of a const reference:
class X {
value_type& operator[](index_type idx);
value_type operator[](index_type idx) const;
// ...
};
Operators for Pointer-like Types
For defining your own iterators or smart pointers, you have to overload the unary prefix dereference operator *
and the binary infix pointer member access operator ->
:
class my_ptr {
value_type& operator*();
const value_type& operator*() const;
value_type* operator->();
const value_type* operator->() const;
};
Note that these, too, will almost always need both a const and a non-const version.
For the ->
operator, if value_type
is of class
(or struct
or union
) type, another operator->()
is called recursively, until an operator->()
returns a value of non-class type.
The unary address-of operator should never be overloaded.
For operator->*()
see this question. It's rarely used and thus rarely ever overloaded. In fact, even iterators do not overload it.
Continue to Conversion Operators
Batchfile to create backup and rename with timestamp
See if this is what you want to do:
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"
MySQL, update multiple tables with one query
When you say multiple queries do you mean multiple SQL statements as in:
UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;
Or multiple query function calls as in:
mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)
The former can all be done using a single mySqlQuery call if that is what you wanted to achieve, simply call the mySqlQuery function in the following manner:
mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)
This will execute all three queries with one mySqlQuery() call.
How to set delay in vbscript
Time of Sleep Function is in milliseconds (ms)
if you want 3 minutes, thats the way to do it:
WScript.Sleep(1000 * 60 * 3)
git push rejected: error: failed to push some refs
If you are the only the person working on the project, what you can do is:
git checkout master
git push origin +HEAD
This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)
How to update ruby on linux (ubuntu)?
Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:
sudo apt-get install ruby2.0
check version
ruby --version
Hope that helps
Error: Unexpected value 'undefined' imported by the module
For me the problem was solved by changing the import sequence :
One with I got the error :
imports: [
BrowserModule, HttpClientModule, AppRoutingModule,
CommonModule
],
Changed this to :
imports: [
BrowserModule, CommonModule, HttpClientModule,
AppRoutingModule
],
Is there a cross-domain iframe height auto-resizer that works?
I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content.
There are some steps to follow to achieve this.
Suppose you have added iframe in "abc.com/page" web page
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
Next you have to bind windows "message" event under web page "abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message:
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
- On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {
// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
Change priorityQueue to max priorityqueue
You can try pushing elements with reverse sign. Eg: To add a=2 & b=5 and then poll b=5.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(-a);
pq.add(-b);
System.out.print(-pq.poll());
Once you poll the head of the queue, reverse the sign for your usage.
This will print 5 (larger element). Can be used in naive implementations. Definitely not a reliable fix. I don't recommend it.
String concatenation of two pandas columns
The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
It's longer than the other answer but is more generic (can be used with values that are not strings).
How to increase MySQL connections(max_connections)?
If you need to increase MySQL Connections without MySQL restart do like below
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 150 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL
max_connections = 150
Angular bootstrap datepicker date format does not format ng-model value
I ran into the same problem and after a couple of hours of logging and investigating, I fixed it.
It turned out that for the first time the value is set in a date picker, $viewValue is a string so the dateFilter displays it as is. All I did is parse it into a Date object.
Search for that block in ui-bootstrap-tpls file
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
and replace it by:
ngModel.$render = function() {
ngModel.$viewValue = new Date(ngModel.$viewValue);
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
Hopefully this will help :)
Postfix is installed but how do I test it?
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
How to call URL action in MVC with javascript function?
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
How to set default values for Angular 2 component properties?
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
How to zero pad a sequence of integers in bash so that all have the same width?
Use awk like this:
awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'
OUTPUT:
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
Update:
As pure bash alternative you can do this to get same output:
for i in {1..10}
do
printf "%05d\n" $i
done
This way you can avoid using an external program seq
which is NOT available on all the flavors of *nix.
Passing struct to function
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
Difference between matches() and find() in Java Regex
find()
will consider the sub-string against the regular expression where as matches()
will consider complete expression.
find()
will returns true only if the sub-string of the expression matches the pattern.
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
Adding quotes to a string in VBScript
I don't think I can improve on these answers as I've used them all, but my preference is declaring a constant and using that as it can be a real pain if you have a long string and try to accommodate with the correct number of quotes and make a mistake. ;)
Replace all 0 values to NA
dplyr::na_if()
is an option:
library(dplyr)
df <- data_frame(col1 = c(1, 2, 3, 0),
col2 = c(0, 2, 3, 4),
col3 = c(1, 0, 3, 0),
col4 = c('a', 'b', 'c', 'd'))
na_if(df, 0)
# A tibble: 4 x 4
col1 col2 col3 col4
<dbl> <dbl> <dbl> <chr>
1 1 NA 1 a
2 2 2 NA b
3 3 3 3 c
4 NA 4 NA d
What is the equivalent of Java static methods in Kotlin?
except Michael Anderson's answer, i have coding with other two way in my project.
First:
you can white all variable to one class.
created a kotlin file named Const
object Const {
const val FIRST_NAME_1 = "just"
const val LAST_NAME_1 = "YuMu"
}
You can use it in kotlin and java code
Log.d("stackoverflow", Const.FIRST_NAME_1)
Second:
You can use Kotlin's extension function
created a kotlin file named Ext, below code is the all code in Ext file
package pro.just.yumu
/**
* Created by lpf on 2020-03-18.
*/
const val FIRST_NAME = "just"
const val LAST_NAME = "YuMu"
You can use it in kotlin code
Log.d("stackoverflow", FIRST_NAME)
You can use it in java code
Log.d("stackoverflow", ExtKt.FIRST_NAME);
Pandas conditional creation of a series/dataframe column
Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:
def map_values(row, values_dict):
return values_dict[row]
values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})
df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))
What's it look like:
df
Out[2]:
INDICATOR VALUE NEW_VALUE
0 A 10 1
1 B 9 2
2 C 8 3
3 D 7 4
This approach can be very powerful when you have many ifelse
-type statements to make (i.e. many unique values to replace).
And of course you could always do this:
df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)
But that approach is more than three times as slow as the apply
approach from above, on my machine.
And you could also do this, using dict.get
:
df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]
How to do a join in linq to sql with method syntax?
Justin has correctly shown the expansion in the case where the join is just followed by a select
. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.
So to change Justin's example slightly:
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
where sc.X + sc.Y == 10
select new { SomeClass = sc, SomeOtherClass = soc }
would be converted into something like this:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new { sc, soc })
.Where(z => z.sc.X + z.sc.Y == 10)
.Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });
The z
here is the transparent identifier - but because it's transparent, you can't see it in the original query :)
Nested iframes, AKA Iframe Inception
Thing is, the code you provided won't work because the <iframe>
element has to have a "src" property, like:
<iframe id="uploads" src="http://domain/page.html"></iframe>
It's ok to use .contents()
to get the content:
$('#uploads).contents()
will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html
document the #uploads iframe loaded.
To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:
$('#uploads').contents().find('iframe').contents().find('#element');
There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.
Hope this helps ...
Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>main.html example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first
setTimeout( function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
}, 2000 );
});
</script>
</head>
<body>
<iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>
iframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>iframe.html example</title>
</head>
<body>
<iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>
noframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>noframe.html example</title>
</head>
<body>
<div id="element">some content</div>
</body>
Prompt for user input in PowerShell
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
Android: Quit application when press back button
I had the Same problem, I have one LoginActivity and one MainActivity.
If I click back button in MainActivity, Application has to close.
SO I did with OnBackPressed method. this moveTaskToBack() work as same as Home Button. It leaves the Back stack as it is.
public void onBackPressed() {
// super.onBackPressed();
moveTaskToBack(true);
}
how to make a cell of table hyperlink
I have also been looking for a solution, and just found this code on another site:
<td style="cursor:pointer" onclick="location.href='mylink.html'">link</td>
Get the client's IP address in socket.io
Since socket.io 1.1.0, I use :
io.on('connection', function (socket) {
console.log('connection :', socket.request.connection._peername);
// connection : { address: '192.168.1.86', family: 'IPv4', port: 52837 }
}
Edit : Note that this is not part of the official API, and therefore not guaranteed to work in future releases of socket.io.
Also see this relevant link :
engine.io issue
C#: calling a button event handler method without actually clicking the button
If the method isn't using either sender
or e
you could call:
btnTest_Click(null, null);
What you probably should consider doing is extracting the code from within that method into its own method, which you could call from both the button click event handler, and any other places in code that the functionality is required.
Get element from within an iFrame
Below code will help you to find out iframe data.
let iframe = document.getElementById('frameId');
let innerDoc = iframe.contentDocument || iframe.contentWindow.document;
how to convert object to string in java
The result is not a String
but a String[]
. That's why you get this unsuspected printout.
[Ljava.lang.String
is a signature of an array of String
:
System.out.println(new String[]{});
mongodb: insert if not exists
In general, using update is better in MongoDB as it will just create the document if it doesn't exist yet, though I'm not sure how to work that with your python adapter.
Second, if you only need to know whether or not that document exists, count() which returns only a number will be a better option than find_one which supposedly transfer the whole document from your MongoDB causing unnecessary traffic.
Adding an arbitrary line to a matplotlib plot in ipython notebook
You can directly plot the lines you want by feeding the plot
command with the corresponding data (boundaries of the segments):
plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)
(of course you can choose the color, line width, line style, etc.)
From your example:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)
# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')
plt.show()
Oracle DateTime in Where Clause?
As other people have commented above, using TRUNC will prevent the use of indexes (if there was an index on TIME_CREATED). To avoid that problem, the query can be structured as
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED BETWEEN TO_DATE('26/JAN/2011','dd/mon/yyyy')
AND TO_DATE('26/JAN/2011','dd/mon/yyyy') + INTERVAL '86399' second;
86399 being 1 second less than the number of seconds in a day.
What is the canonical way to trim a string in Ruby without creating a new string?
If you are using Ruby on Rails there is a squish
> @title = " abc "
=> " abc "
> @title.squish
=> "abc"
> @title
=> " abc "
> @title.squish!
=> "abc"
> @title
=> "abc"
If you are using just Ruby you want to use strip
Herein lies the gotcha.. in your case you want to use strip without the bang !
while strip! certainly does return nil if there was no action it still updates the variable so strip! cannot be used inline. If you want to use strip inline you can use the version without the bang !
strip! using multi line approach
> tokens["Title"] = " abc "
=> " abc "
> tokens["Title"].strip!
=> "abc"
> @title = tokens["Title"]
=> "abc"
strip single line approach... YOUR ANSWER
> tokens["Title"] = " abc "
=> " abc "
> @title = tokens["Title"].strip if tokens["Title"].present?
=> "abc"
How to declare and display a variable in Oracle
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
setting system property
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
How to validate numeric values which may contain dots or commas?
\d
means a digit in most languages. You can also use [0-9]
in all languages. For the "period or comma" use [\.,]
. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.
*
means "zero-or-more", so \d*
and [0-9]*
mean "zero or more numbers". ?
means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n}
to mean "between m and n" (ie: {1,2} means "between 1 and 2")
Since the dot or comma and additional numbers are optional, you can put them in a group and use the ?
quantifier to mean "zero-or-one" of that group.
Putting that all together you can use:
\d{1,2}([\.,][\d{1,2}])?
Meaning, one or two digits \d{1,2}
, followed by zero-or-one of a group (...)?
consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}
JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")
You should never use the unidirectional @OneToMany
annotation because:
- It generates inefficient SQL statements
- It creates an extra table which increases the memory footprint of your DB indexes
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Error importing Seaborn module in Python
I had faced the same problem. Restarting the notebook solved my problem.
If that doesn't solve the problem, you can try this
pip install seaborn
Edit
As few people have posted in the comments, you can also use
python -m pip install seaborn
Plus, as per https://bugs.python.org/issue22295 it is a better way because in this case, you can specify which version of python (python3 or python2) to use for running pip
How do I run a simple bit of code in a new thread?
There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.
There is a good async method article at the Code Project web site that describes the various methods and provides sample code.
Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.
Python - How to convert JSON File to Dataframe
There are 2 inputs you might have and you can also convert between them.
- input: listOfDictionaries --> use @VikashSingh solution
example: [{"":{"...
The pd.DataFrame() needs a listOfDictionaries as input.
- input: jsonStr --> use @JustinMalinchak solution
example: '{"":{"...
If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:
jsonStr = json.dumps(listOfDictionaries)
Thus, switch back from jsonStr to listOfDictionaries first:
listOfDictionaries = json.loads(jsonStr)
Delete duplicate records from a SQL table without a primary key
Use the row number to differentiate between duplicate records. Keep the first row number for an EmpID/EmpSSN and delete the rest:
DELETE FROM Employee a
WHERE ROW_NUMBER() <> ( SELECT MIN( ROW_NUMBER() )
FROM Employee b
WHERE a.EmpID = b.EmpID
AND a.EmpSSN = b.EmpSSN )
An unhandled exception was generated during the execution of the current web request
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
log4j:WARN No appenders could be found for logger in web.xml
Or, you could be doing what I did and define the logger before the log configuration file has been loaded. This would be as they say: "Putting the cart before the horse."
In the code:
public static Logger logger = Logger.getLogger("RbReport");
...
later on
PropertyConfigurator.configure(l4j);
logger = Logger.getLogger("RbReport");
Fix was to initialize the logger after the configuration was loaded.
For the geeks it was "Putting Descarte b4 d horse".
Performing user authentication in Java EE / JSF using j_security_check
It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.
java.net.URL read stream to byte[]
There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
You'll then have the image data in baos
, from which you can get a byte array by calling baos.toByteArray()
.
This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.
Looping from 1 to infinity in Python
Using itertools.count
:
import itertools
for i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
In Python 2, range()
and xrange()
were limited to sys.maxsize
. In Python 3 range()
can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it's probably best to use count()
.
Convert an image (selected by path) to base64 string
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
var imageStream = new MemoryStream();
try
{
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
var ImageBase64 = Convert.ToBase64String(imageBytes);
return ImageBase64;
}
catch (Exception ex)
{
return "Error converting image to base64!";
}
finally
{
imageStream.Dispose;
}
}
Node.js: How to send headers with form data using request module?
Just remember set method to POST in options. Here is my code
var options = {
url: 'http://www.example.com',
method: 'POST', // Don't forget this line
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
},
form: {
'key-1':'value-1',
'key-2':'value-2',
...
}
};
//console.log('options:', options);
// Create request to get data
request(options, (err, response, body) => {
if (err) {
//console.log(err);
} else {
console.log('body:', body);
}
});
Printing result of mysql query from variable
This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
Spaces in URLs?
A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses +
instead of %20
for spaces).
But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20
is not a space (obviously) but it represents a space.
How to set tbody height with overflow scroll
In my case I wanted to have responsive table height instead of fixed height in pixels as the other answers are showing. To do that I used percentage of visible height property and overflow on div containing the table:
&__table-container {
height: 70vh;
overflow: scroll;
}
This way the table will expand along with the window being resized.
Overloading operators in typedef structs (c++)
The breakdown of your declaration and its members is somewhat littered:
Remove the typedef
The typedef
is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos
as-written, which is core to your current compilation failure.
Change this:
typedef struct {....} pos;
To this:
struct pos { ... };
Remove extraneous inlines
You're both declaring and defining your member operators within the class definition itself. The inline
keyword is not needed so long as your implementations remain in their current location (the class definition)
Return references to *this
where appropriate
This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:
a = b = c;
This assigns c
to b
, and the resulting value b
is then assigned to a
. This is not equivalent to the following code, contrary to what you may think:
a = c;
b = c;
Therefore, your assignment operator should be implemented as such:
pos& operator =(const pos& a)
{
x = a.x;
y = a.y;
return *this;
}
Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)
Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:
pos& operator=(pos a) // by-value param invokes class copy-ctor
{
this->swap(a);
return *this;
}
Then a swap method is implemented:
void pos::swap(pos& obj)
{
// TODO: swap object guts with obj
}
You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.
Pass objects by const reference when appropriate
All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:
Change this:
bool operator==(pos a) const{
if(a.x==x && a.y== y)return true;
else return false;
}
To this: (also simplified)
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
No copies of anything are made, resulting in more efficient code.
Finally, in answering your question, what is the difference between a member function or operator declared as const
and one that is not?
A const
member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const
member functions can be invoked against const
objects, or const
references and pointers. For example, your operator +()
does not modify your local object and thus should be declared as const
. Your operator =()
clearly modifies the local object, and therefore the operator should not be const
.
Summary
struct pos
{
int x;
int y;
// default + parameterized constructor
pos(int x=0, int y=0)
: x(x), y(y)
{
}
// assignment operator modifies object, therefore non-const
pos& operator=(const pos& a)
{
x=a.x;
y=a.y;
return *this;
}
// addop. doesn't modify object. therefore const.
pos operator+(const pos& a) const
{
return pos(a.x+x, a.y+y);
}
// equality comparison. doesn't modify object. therefore const.
bool operator==(const pos& a) const
{
return (x == a.x && y == a.y);
}
};
EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:
a = b = c;
Is equivalent to this:
b = c;
a = b;
And that this does not always equate to this:
a = c;
b = c;
Sample code:
#include <iostream>
#include <string>
using namespace std;
struct obj
{
std::string name;
int value;
obj(const std::string& name, int value)
: name(name), value(value)
{
}
obj& operator =(const obj& o)
{
cout << name << " = " << o.name << endl;
value = (o.value+1); // note: our value is one more than the rhs.
return *this;
}
};
int main(int argc, char *argv[])
{
obj a("a", 1), b("b", 2), c("c", 3);
a = b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
a = c;
b = c;
cout << "a.value = " << a.value << endl;
cout << "b.value = " << b.value << endl;
cout << "c.value = " << c.value << endl;
return 0;
}
Output
b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3
How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function
Exchange rate from Euro to NOK on the first of January 2016:
=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)
The INDEX()
function is used because GOOGLEFINANCE()
function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.
Custom Drawable for ProgressBar/ProgressDialog
public class CustomProgressBar {
private RelativeLayout rl;
private ProgressBar mProgressBar;
private Context mContext;
private String color__ = "#FF4081";
private ViewGroup layout;
public CustomProgressBar (Context context, boolean isMiddle, ViewGroup layout) {
initProgressBar(context, isMiddle, layout);
}
public CustomProgressBar (Context context, boolean isMiddle) {
try {
layout = (ViewGroup) ((Activity) context).findViewById(android.R.id.content).getRootView();
} catch (Exception e) {
e.printStackTrace();
}
initProgressBar(context, isMiddle, layout);
}
void initProgressBar(Context context, boolean isMiddle, ViewGroup layout) {
mContext = context;
if (layout != null) {
int padding;
if (isMiddle) {
mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleSmall);
// mProgressBar.setBackgroundResource(R.drawable.pb_custom_progress);//Color.parseColor("#55000000")
padding = context.getResources().getDimensionPixelOffset(R.dimen.padding);
} else {
padding = context.getResources().getDimensionPixelOffset(R.dimen.padding);
mProgressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleSmall);
}
mProgressBar.setPadding(padding, padding, padding, padding);
mProgressBar.setBackgroundResource(R.drawable.pg_back);
mProgressBar.setIndeterminate(true);
try {
color__ = AppData.getTopColor(context);//UservaluesModel.getAppSettings().getSelectedColor();
} catch (Exception e) {
color__ = "#FF4081";
}
int color = Color.parseColor(color__);
// color=getContrastColor(color);
// color__ = color__.replaceAll("#", "");//R.color.colorAccent
mProgressBar.getIndeterminateDrawable().setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_ATOP);
}
}
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rl = new RelativeLayout(context);
if (!isMiddle) {
int valueInPixels = (int) context.getResources().getDimension(R.dimen.padding);
lp.setMargins(0, 0, 0, (int) (valueInPixels / 1.5));//(int) Utils.convertDpToPixel(valueInPixels, context));
rl.setClickable(false);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
} else {
rl.setGravity(Gravity.CENTER);
rl.setClickable(true);
}
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mProgressBar.setScaleY(1.55f);
mProgressBar.setScaleX(1.55f);
mProgressBar.setLayoutParams(lp);
rl.addView(mProgressBar);
layout.addView(rl, params);
}
}
public void show() {
if (mProgressBar != null)
mProgressBar.setVisibility(View.VISIBLE);
}
public void hide() {
if (mProgressBar != null) {
rl.setClickable(false);
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
And then call
customProgressBar = new CustomProgressBar (Activity, true);
customProgressBar .show();
What is the difference between '/' and '//' when used for division?
/ --> Floating point division
// --> Floor division
Lets see some examples in both python 2.7 and in Python 3.5.
Python 2.7.10 vs. Python 3.5
print (2/3) ----> 0 Python 2.7
print (2/3) ----> 0.6666666666666666 Python 3.5
Python 2.7.10 vs. Python 3.5
print (4/2) ----> 2 Python 2.7
print (4/2) ----> 2.0 Python 3.5
Now if you want to have (in python 2.7) same output as in python 3.5, you can do the following:
Python 2.7.10
from __future__ import division
print (2/3) ----> 0.6666666666666666 #Python 2.7
print (4/2) ----> 2.0 #Python 2.7
Where as there is no differece between Floor division in both python 2.7 and in Python 3.5
138.93//3 ---> 46.0 #Python 2.7
138.93//3 ---> 46.0 #Python 3.5
4//3 ---> 1 #Python 2.7
4//3 ---> 1 #Python 3.5
How to kill all processes matching a name?
If you're using cygwin or some minimal shell that lacks killall
you can just use this script:
killall.sh - Kill by process name.
#/bin/bash
ps -W | grep "$1" | awk '{print $1}' | xargs kill --
Usage:
$ killall <process name>
Handlebars/Mustache - Is there a built in way to loop through the properties of an object?
This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.
var data = {
valueFromMap: function() {
return function(text, render) {
// "this" will be an object with map key property
// text will be color that we have between the mustache-tags
// in the template
// render is the function that mustache gives us
// still need to loop since we have no idea what the key is
// but there will only be one
for ( var key in this) {
if (this.hasOwnProperty(key)) {
return render(this[key][text]);
}
}
};
},
list: {
blueHorse: {
color: 'blue'
},
redHorse: {
color: 'red'
}
}
};
Template:
{{#list}}
{{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}
Outputs:
color: blue
color: red
(order might be random - it's a map)
This might be useful if you know the map element that you want. Just watch out for falsy values.
Creating folders inside a GitHub repository without using Git
After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.
When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.
For example, if I would like to create the file filename.md
in a series of sub-folders, I can do this (taken from the GitHub blog):
How to use SearchView in Toolbar Android
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Check/Uncheck a checkbox on datagridview
// here is a simple way to do so
//irate through the gridview
foreach (DataGridViewRow row in PifGrid.Rows)
{
//store the cell (which is checkbox cell) in an object
DataGridViewCheckBoxCell oCell = row.Cells["Check"] as DataGridViewCheckBoxCell;
//check if the checkbox is checked or not
bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
//if its checked then uncheck it other wise check it
if (!bChecked)
{
row.Cells["Check"].Value = true;
}
else
{
row.Cells["Check"].Value = false;
}
}
How to show two figures using matplotlib?
I had this same problem.
Did:
f1 = plt.figure(1)
# code for figure 1
# don't write 'plt.show()' here
f2 = plt.figure(2)
# code for figure 2
plt.show()
Write 'plt.show()' only once, after the last figure.
Worked for me.
Convert .pem to .crt and .key
Converting Using OpenSSL
These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.
Convert a DER file (.crt .cer .der) to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
Convert a PEM file to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Convert PEM to CRT (.CRT file)
openssl x509 -outform der -in certificate.pem -out certificate.crt
OpenSSL Convert PEM
Convert PEM to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert PEM to P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
Convert PEM to PFX
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
OpenSSL Convert DER
OpenSSL Convert P7B
Convert P7B to PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
Convert P7B to PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
OpenSSL Convert PFX
Generate rsa keys by OpenSSL
Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.
openssl genrsa -out private.pem 1024
This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
or
openssl rsa -in private.pem -pubout > public.pem
or
openssl rsa -in private.pem -pubout -out public.pem
You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties.
You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:
Example file :
echo 'too many secrets' > file.txt
You now have some data in file.txt, lets encrypt it using OpenSSL and
the public key:
openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
This creates an encrypted version of file.txt calling it file.ssl, if
you look at this file it’s just binary junk, nothing very useful to
anyone. Now you can unencrypt it using the private key:
openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
You will now have an unencrypted file in decrypted.txt:
cat decrypted.txt
|output -> too many secrets
RSA TOOLS Options in OpenSSL
NAME
rsa - RSA key processing tool
SYNOPSIS
openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]
DESCRIPTION
The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.
COMMAND OPTIONS
-help
Print out a usage message.
-inform DER|NET|PEM
This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.
-outform DER|NET|PEM
This specifies the output format, the options have the same meaning as the -inform option.
-in filename
This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.
-passin arg
the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-out filename
This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.
-passout password
the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea
These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.
-text
prints out the various public or private key components in plain text in addition to the encoded version.
-noout
this option prevents output of the encoded version of the key.
-modulus
this option prints out the value of the modulus of the key.
-check
this option checks the consistency of an RSA private key.
-pubin
by default a private key is read from the input file: with this option a public key is read instead.
-pubout
by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.
-RSAPublicKey_in, -RSAPublicKey_out
like -pubin and -pubout except RSAPublicKey format is used instead.
-engine id
specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.
NOTES
The PEM private key format uses the header and footer lines:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
The PEM public key format uses the header and footer lines:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
The PEM RSAPublicKey format uses the header and footer lines:
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.
Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string "private-key", then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.
EXAMPLES
To remove the pass phrase on an RSA private key:
openssl rsa -in key.pem -out keyout.pem
To encrypt a private key using triple DES:
openssl rsa -in key.pem -des3 -out keyout.pem
To convert a private key from PEM to DER format:
openssl rsa -in key.pem -outform DER -out keyout.der
To print out the components of a private key to standard output:
openssl rsa -in key.pem -text -noout
To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
Output the public part of a private key in RSAPublicKey format:
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
Why is my method undefined for the type object?
It should be like that
public static void main(String[] args) {
EchoServer0 e = new EchoServer0();
// TODO Auto-generated method stub
e.listen();
}
Your variable of type Object
truly doesn't have such a method, but the type EchoServer0
you define above certainly has.
Date format in dd/MM/yyyy hh:mm:ss
CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END
how to create a list of lists
You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:
>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]
Getting the number of filled cells in a column (VBA)
You can also use
Cells.CurrentRegion
to give you a range representing the bounds of your data on the current active sheet
Msdn says on the topic
Returns a Range object that represents
the current region. The current region
is a range bounded by any combination
of blank rows and blank columns.
Read-only.
Then you can determine the column count via
Cells.CurrentRegion.Columns.Count
and the row count via
Cells.CurrentRegion.Rows.Count
Can you style an html radio button to look like a checkbox?
Simple and neat with fontawesome
input[type=radio] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
outline: none;
content: none;
margin-left: 5px;
}
input[type=radio]:before {
font-family: "FontAwesome";
content: "\f00c";
font-size: 25px;
color: transparent !important;
background: #fff;
width: 25px;
height: 25px;
border: 2px solid black;
margin-right: 5px;
}
input[type=radio]:checked:before {
color: black !important;
}
how can get index & count in vuejs
The optional SECOND argument is the index, starting at 0. So to output the index and total length of an array called 'some_list':
<div>Total Length: {{some_list.length}}</div>
<div v-for="(each, i) in some_list">
{{i + 1}} : {{each}}
</div>
If instead of a list, you were looping through an object, then the second argument is key of the key/value pair. So for the object 'my_object':
var an_id = new Vue({
el: '#an_id',
data: {
my_object: {
one: 'valueA',
two: 'valueB'
}
}
})
The following would print out the key : value pairs. (you can name 'each' and 'i' whatever you want)
<div id="an_id">
<span v-for="(each, i) in my_object">
{{i}} : {{each}}<br/>
</span>
</div>
For more info on Vue list rendering: https://vuejs.org/v2/guide/list.html
Inner join with count() on three tables
It makes more sense to join the item with the orders than with the people !
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON orders.pe_id = people.pe_id
INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
people.pe_id;
Joining the items with the people provokes a lot of doublons.
For example, the cake items in order 3 will be linked with the order 2 via the join between the people, and you don't want this to happen !!
So :
1- You need a good understanding of your schema. Items are link to orders, and not to people.
2- You need to count distinct orders for one person, else you will count as many items as orders.
how to automatically scroll down a html page?
You can use two different techniques to achieve this.
The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;
).
The second is setting the link to point to a specific id in the page e.g.
<a href="mypage.html#sectionOne">section one</a>
Then if in your target page you'll have that ID the page will be scrolled automatically.
Join/Where with LINQ and Lambda
It could be something like
var myvar = from a in context.MyEntity
join b in context.MyEntity2 on a.key equals b.key
select new { prop1 = a.prop1, prop2= b.prop1};
Delaying AngularJS route change until model loaded to prevent flicker
$routeProvider resolve property allows delaying of route change until data is loaded.
First define a route with resolve
attribute like this.
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: PhoneListCtrl,
resolve: PhoneListCtrl.resolve}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: PhoneDetailCtrl,
resolve: PhoneDetailCtrl.resolve}).
otherwise({redirectTo: '/phones'});
}]);
notice that the resolve
property is defined on route.
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone, $q) {
// see: https://groups.google.com/forum/?fromgroups=#!topic/angular/DGf7yyD4Oc4
var deferred = $q.defer();
Phone.query(function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject(); // you could optionally pass error data here
});
return deferred.promise;
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
Notice that the controller definition contains a resolve object which declares things which should be available to the controller constructor. Here the phones
is injected into the controller and it is defined in the resolve
property.
The resolve.phones
function is responsible for returning a promise. All of the promises are collected and the route change is delayed until after all of the promises are resolved.
Working demo: http://mhevery.github.com/angular-phonecat/app/#/phones
Source: https://github.com/mhevery/angular-phonecat/commit/ba33d3ec2d01b70eb5d3d531619bf90153496831
About catching ANY exception
Very simple example, similar to the one found here:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
In the above example, you'd see output in this order:
1) Performing an action which may throw an exception.
2) Finally is called directly after executing the try statement whether an exception is thrown or not.
3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.
Hope this helps!
ReferenceError: fetch is not defined
The following works for me in Node.js 12.x:
npm i node-fetch;
to initialize the Dropbox instance:
var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
accessToken: <your access token>,
fetch: require("node-fetch")
});
to e.g. upload a content (an asynchronous method used in this case):
await dbx.filesUpload({
contents: <your content>,
path: <file path>
});
Getting a Request.Headers value
if (Request.Headers["XYZComponent"].Count() > 0)
... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:
Use this instead:
if(Request.Headers["XYZComponent"] != null)
Or if you want to treat blank or empty strings as not set then use:
if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)
The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.
A variation of your second attempt will also work:
if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))
Edit: Sorry didn't realise you were explicitly checking for the value true:
bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'
How do I ignore all files in a folder with a Git repository in Sourcetree?
For Sourcetree users: If you want to ignore a specific folder, just select a file from this folder, right-click on it and do "Ignore...". You will have a pop-up menu where you can ignore "Ignore everything beneath: <YOUR UNWANTED FOLDER>"
If you have the "Ignore" option greyed out, you have to select the "Stop Tracking" option. After that the file will be added to Staged files with a minus sign on red background icon and the file's icon in Unstaged files list will change to a question sign on a violet background. Now in Unstaged files list, the "Ignore" option is enabled again. Just do as described above.
What is Options +FollowSymLinks?
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
Redirect in Spring MVC
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
Define: What is a HashSet?
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
How to activate "Share" button in android app?
Create a button with an id share and add the following code snippet.
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
The above code snippet will open the share chooser on share button click action.
However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.
Delaying function in swift
You can use GCD (in the example with a 10 second delay):
Swift 2
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
Swift 3 and Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
Swift 5 or Later
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
Having a UITextField in a UITableViewCell
This should not be difficult. When creating a cell for your table, add a UITextField object to the cell's content view
UITextField *txtField = [[UITextField alloc] initWithFrame....]
...
[cell.contentView addSubview:txtField]
Set the delegate of the UITextField as self (ie your viewcontroller) Give a tag to the text field so you can identify which textfield was edited in your delegate methods. The keyboard should pop up when the user taps the text field. I got it working like this. Hope it helps.
private final static attribute vs private final attribute
Furthermore to Jon's answer if you use static final it will behave as a kind-of "definition". Once you compile the class which uses it, it will be in the compiled .class file burnt.
Check my thread about it here.
For your main goal: If you don't use the NUMBER differently in the different instances of the class i would advise to use final and static.
(You just have to keep in mind to not to copy compiled class files without considering possible troubles like the one my case study describes. Most of the cases this does not occur, don't worry :) )
To show you how to use different values in instances check this code:
public class JustFinalAttr {
public final int Number;
public JustFinalAttr(int a){
Number=a;
}
}
...System.out.println(new JustFinalAttr(4).Number);