summary
stringlengths 15
147
| text
stringlengths 1
19.3k
| answer
stringlengths 32
22.6k
| labels
float64 0.33
1
| answer_summary
stringlengths 5
164
|
---|---|---|---|---|
What exactly is 'anti-aliased image generation'?
|
I tried to google it, but didn't quite get it. Any help and/or examples?
Thank you!
|
Anti-aliasing smooths out the text and features so it looks better and in many cases makes it easier to read.
| 0.888889 |
Anti-aliasing smooths out the text and features so it looks better and makes it easier to read
|
Removing oil filter from Lincoln Mark VIII
|
I've had two different Lincoln Mark VIIIs - one 1993, and currently one 1996 LSC. Both are "first generation" ('93-'96) Mark VIIIs, but I'm fairly certain this will also apply to "second generation" ('97-'98) models.
The problem is that the oil filter is in one of the most inconvenient places ever conceivable. Usually, with relatively little trouble, I can get my arm in well enough to unscrew and pull the filter off. But, when it comes to actually getting the filter out from the confined space that is its home, there always seems to be some form of creative contortionism required and I can never seem to remember how it is I got the thing out the last time.
Is there any "easy way" to go about doing this? Is there some trick or special technique I might be missing out on?
|
I can sympathize - ill-located greasy oil filters are a pain to get off. A few tips.
use the FRAM filters that have the grippy/rubberized surface designed to give your fingers some purchase upon removal.
try a combination of oil filter wrenches (the ones designed to go into a 3/8" drive ratchet) and extensions, u-joints, etc if space permits.
get one of those rubber non-slip mats designed to line drawers and wrap it around the oil filter one or more times. This will give you a decent bit of grip to power the filter off.
if you're so inclined, get a remote oil filter relocation kit. This is an adapter with some oil lines that will let you mount the oil filter some place more convenient. As an added bonus, a lot of these kits will let you mount a much larger oil filter as well.
| 1 |
ill-located greasy oil filters are a pain to get off
|
Splitting a file using AWK on Mac OS X
|
I am trying to split a file using AWK on a specific separator. The awk code looks like this:
awk '/SEPARATOR/{n++}{print > "part" n ".txt" }' in.txt
this code works perfectly on my Linux systems. But when running exactly the same code on Mac OS X i get the following error:
awk: syntax error at source line 1
context is
/SEPARATOR/{n++}{print > "part" >>> n <<< ".txt" }
awk: illegal statement at source line 1
I assume that this is some kind of difference between the awk that ships with OS X and mawk from Linux. Removing the string concatenation in the print gets the awk program to work on both platforms, but I would prefer to keep the prefix and surfix. How do I write an awk program that splits a file on a separator into multiple numbered parts and works on both platforms?
|
You can fix this script by using a variable:
awk '/SEPARATOR/{n++}{filename = "part" n ".txt"; print >filename }' in.txt
| 0.888889 |
awk '/SEPARATOR/n++filename = "part"
|
Can I use Flatiron's resourceful in express?
|
Is it possible to use Flatiron's resourcefull (ODM) in express.js?
|
Yes.
You'll want to use express's resource router project, https://github.com/visionmedia/express-resource/. This will require a little bit of setup since you'll need to map each resourceful method call.
I would recommend looking at Flatiron's resource router https://github.com/flatiron/restful, since it requires zero-configuration for working with Resourceful resources.
| 1 |
How to map each resourceful method call
|
dynamic space partitioning tree data structures?
|
I have an application where I need to do nearest neighbor, rectangle/polygon overlap and other basic computational geometry operations against dynamically changing data (all 2d.) I understand the basic data structures in the static case (quadtrees, 2-dimensional Kd-trees, R-trees, BSP, etc.) but I want to understand the state of the art in the dynamic case. The difficulty seems to be knowning when/how to balance on insertion and deletion. For example, is there a dynamic data structure that answers k-nearest neighbors against n points in O(log n + k), where insertion and deletion take O(log n) (amortized, maybe)? Is there a standard reference that summarizes what's known about this problem?
|
To be honest, I haven't done too much with dynamic trees myself (mostly static). But I believe the Bkd-tree paper (early 2000s?) is good source to start. I believe it has been referenced many times since then. You can use sources like acm/citeseer to track newer papers that reference it. Side note: i think there is public code available for Bkds so you can play with it without investing too much time - see if it works for you.
Bkd-Tree: A Dynamic Scalable kd-Tree
Octavian Procopiuc, Pankaj K. Agarwal, Lars Arge, and Jeffrey Scott Vitter
| 0.555556 |
Bkd-Tree paper (early 2000s?) is good source to start.
|
put an html (scripted) menu in a separate file
|
I have a menu that I've created using jquery that "pops-up" on certain button mouse-overs.
it has a LOT of options and sub-menu options and I'd like to put it into a separate file so that it only needs to be downloaded once and all of the html markup and text doesn't need to be re-downloaded every time a user hits a sub page on my site.
I was toying with the idea of using the jquery template engine but couldn't quite wrap my head around the best way to work that. This isn't a template after all, but a static menu.
I'm pretty sure I can't put it in a JS file because it's not script per se, it's actual html markup (mostly tables).
Any ideas?
|
So in conclusion this would be the only way to cache the menu individually (or any individual html elements) but bear in mind this would generate an extra http request the first time a user arrives at your site which may not be worth the 50k you're saving versus using serer side includes or php include()
$(function(){
$("#menuholder").html("all the menu markup goes in here");
}) <!-- inside menu.js
<script src="menu.js"></script>
<div id="menuholder"></div>
| 0.555556 |
Cache the menu individually or any individual html elements
|
Reflection across the plane
|
Let $T: \Bbb R^3 \rightarrow \Bbb R^3$ be the linear transformation given by reflecting across the plane $S=\{x:-x_1+x_2+x_3=0\}$ (...)
Then, $S=\gen[(1,1,0),(1,0,1)]\$
But how can I get the matrix $R_v$ such that reflects across $S$?
Thanks!
|
$R$ is the matrix whose columns are the results of reflecting $(1,0,0)$, $(0,1,0)$, and $(0,0,1)$ across $S$. So, can you work out the result of reflecting each of those three vectors across $S$?
| 0.777778 |
Can you work out the results of reflecting $(1,0,0)$, $(0,1)$ & $ (0
|
Office 365 SharePoint v1.0 API Authorization Issue
|
I have a client app that uses the Office 365 SharePoint preview API. Recently (as of October 2014), Microsoft published version 1.0 of that API. The authentication steps used with the preview API no longer work with version 1.0.
To demonstrate the problem I have created a short node.js script. The script does the following:
Authorizes by launching a browser. Gives a redirect URL to localhost and launches a server to catch the redirect post-authorization
POST to https://login.windows.net/common/oauth2/token to get an access token
GET to the Office 365 discovery service to get the SharePoint API endpoint
POST to https://login.windows.net/common/oauth2/token with a refresh token to get a new access token
GET to the SharePoint API endpoint to get a list of files
The script can be used with the preview API and version 1.0 of the API. It is able to get a JSON list of files from the preview API, but fails with the following for version 1.0 (on the last call):
{
"error": {
"code": "-2147024891, System.UnauthorizedAccessException",
"message": "Access denied. You do not have permission to perform this action or access this resource."
}
}
Does anybody see anything wrong with the sequence of calls?
Please take a look at the sample script for more details.
|
In looking at your scripts, it looks like you are using a hard coded resource ID ("Microsoft.SharePoint"), when I believe the new one is ("domain-my.sharepoint.com"). If using multi-tenant, it will be dynamic and available from the discovery call and likely the id you should use each time. If you have single tenant, then I suppose you could hard code it.
| 0.888889 |
Multi-tenant resource ID
|
Replicate a big, dense Windows volume over a WAN -- too big for DFS-R
|
I've got a server with a LOT of small files -- many millions files, and over 1.5 TB of data. I need a decent backup strategy.
Any filesystem-based backup takes too long -- just enumerating which files need to be copied takes a day.
Acronis can do a disk image in 24 hours, but fails when it tries to do a differential backup the next day.
DFS-R won't replicate a volume with this many files.
I'm starting to look at Double Take, which seems to be able to do continuous replication. Are there other solutions that can do continuous replication at a block or sector level -- not file-by-file over a WAN?
Some details:
The files are split up into about 75,000 directories.
99% of the daily change comes from adding new directories; existing files are rarely changed.
There's some other relevant discussion here.
|
1.5 TB would take 30 minutes with http://www.exdupe.com/ :p
... given that your disks are fast enough (exdupe is so fast that it's IO bound, not CPU bound).
And I havn't reached any limits on file count yet. Had millions too.
Edit: Ah, you need a partition/sector based backup and not file system level? It can't do that... Maybe http:// www . drivesnapshot.de/en/ is worth a shot (had to add spaces because of spam protection). Does diff backups and shadow volume copy too (no reboot).
| 0.888889 |
Does diff backups and shadow volume copy
|
How often do I need to change my oil in a VW TDI?
|
The manual for my 2003 VW TDI says to change the oil every 12 months or 10,000 miles. My dealer says every 6 months or 5,000 miles.
Are they just trying to make twice as much money off my oil changes, or is there a legitimate reason to change the oil twice as often as VW originally printed in the book?
|
I change the oil every 18,000 miles. My tdi is on longlife service plan and I use only the best long life oil.
| 1 |
I change the oil every 18,000 miles
|
Matrix Manipulation Question
|
Given that A $\begin{bmatrix}1\\-2\\1\end{bmatrix}=\begin{bmatrix}2\\-3\\-5\end{bmatrix}$ and A $\begin{bmatrix}1\\4\\-2\end{bmatrix}=\begin{bmatrix}0\\2\\-1\end{bmatrix}$ find A $\begin{bmatrix}1 && 1\\-2 && 4\\1 && -2\end{bmatrix}$
Not really sure how to approach this question. Help would be much appreciated :)
|
Hint: $A[v_1 v_2] = [Av_1 Av_2]$
| 1 |
$A[v_1 v_2] = [Av_1. Av_2.
|
How to edit error messages in devise
|
I need to modify the error messages of devise. I want to change the message "is Invalid" to "Es inválido" . The problem is that I have to go to change these messages in the gem. Can I overwrite these messages in the model User
Rails console
1.9.3-p547 :014 > user.save
=> false
1.9.3-p547 :015 > user.errors
=> {:email=>["is invalid"], :password=>["is too short (minimum is 6 characters)"]}
1.9.3-p547 :016 >
User model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
|
You can do the devise specific translations using the
devise.es.yml in your config/locales folder
List of all the different translations is given here in official devise wiki
| 1 |
devise specific translations using devise.es.yml
|
Reading XML in C#
|
This seems like rather too much nesting:
using (XmlReader reader = XmlReader.Create(filename))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Width":
map.Width = ParseXMLValue(reader);
break;
case "Height":
map.Height = ParseXMLValue(reader);
break;
case "TileSize":
map.TileSize = ParseXMLValue(reader);
break;
case "Layers":
map.LayerCount = ParseXMLValue(reader);
break;
case "Layout":
ParseLayout(reader);
break;
case "Layer":
currentLayerIndex = ParseLayer(reader);
break;
case "CollisionLayer":
currentLayerIndex = ParseCollisionLayer();
break;
case "Row":
ParseRow(reader);
break;
}
}
}
}
This is ParseXMLValue(reader):
private int ParseXMLValue(XmlReader reader)
{
reader.Read();
return int.Parse(reader.Value);
}
I'm new to reading XML in C#. Surely there is a better way?
|
I always prefer working with POCO objects instead of Xml documents. If I correctly understand, you just want to parse an xml file into a set of objects.
To do so you need to:
Define objects model - that's it, just create a set of classes you want to get after deserialization. There are should be a root class that stands for the root xml element.
Put correct attributes into the properties of the classes. That's how you will bind properties with xml elements/attributes
Use XmlSerializer to deserialize the file into a normal POCO classes.
See a good explanation here - http://www.agiledeveloper.com/articles/XMLSerialization.pdf
| 0.666667 |
XmlSerializer to parse a file into a set of objects
|
on mouse over background change in document.write
|
I need to change the background image on mouseover, but don't know how to do it as it is in a document.write that I did not write. Any help is appreciated. Here is what I have so far. I want B to be whats there normally and MO on the mouseover.
<script type="text/javascript">
function DrawRow (Link,Status) {
B = "../Images/GreenButton.png" ;
MO = "../Images/GreenButtonMouseOver.png" ;
color1 = "#66FF33"; color2="#000000"; color3="#000000"; color4="#000000"; color5="#000000";
//====================================================================================================================
// Check User Defined States By Rule
//====================================================================================================================
if ( Status4 ) { B="../Images/BlueButton.png"; MO="../Images/BlueButtonMouseOver.png"; color1="#FFFFFF"; }
if ( Status32 ) { B="../Images/LightGreenButton.png"; B="../Images/LightGreenButtonMouseOver.png"; C1color="#000000"; }
if ( Status2 ) { B="../Images/YellowButton.png"; MO="../Images/YellowButtonMouseOver.png"; C1color="#000000"; }
if ( Status1 ) { B="../Images/OrangeButton.png"; MO="../Images/OrangeButtonMouseOver.png"; C1color="#000000"; }
if ( Status8 ) { B="../Images/RedButton.png"; MO="../Images/RedButtonMouseOver.png";C1color="#FFFF00"; }
if ( Status16 ) { B="../Images/PurpleButton.png"; MO="../Images/PurpleButtonMouseOver.png"; C1color="#000000"; }
document.write( "<td ONCLICK=\"Jump('"+Link+"')\"onmouseover=\"this.style.cursor='hand'\" height='37' width='350' background='"+B+"' ><font color='"+color1+"'><p align='center'><b>"+T+"</b></td>" );
|
Finally figured it out here is what I had to do pretty simple, it just took 3 days of trying functions, using stylying sheets then I got this! Thanks everyone for their help I upvoted all for contributing!
document.write( "<td ONCLICK=\"Jump('"+Link+"')\" onmouseover=\"this.style.background='url("+M+")'; this.style.cursor='pointer';\" onmouseout=\"this.style.background='url("+B+")';\" onmousedown=\"this.style.background='url(../Images/Gold-360-ButtonMouseOver.png)'\" height='25' width='350' background='"+B+"' ><p align='center'><font color='"+C1color+"'><b>"+T+"</b></td>" );
| 1 |
How to use stylying sheets?
|
Ajax HTTP error occured. HTTP Result code: 200
|
I get Ajax error when I click next button. You can test it here.
I have found out the problem. It is due to the custom module which I have made.
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<?php
/**
* Implements hook_block_info().
*
* This hook declares what blocks are provided by the module.
*/
function custom_module_block_info()
{
$blocks['tag_cloud'] = array(
// The name that will appear in the block list.
'info' => t('Custom Moudle'),
// Default setting.
'cache' => DRUPAL_CACHE_PER_ROLE
);
return $blocks;
}
When I remove the first two line (Doctype and meta). It works fine. But If I remove first two lines. It doesn't work on IE. I had to insert these two statements to get it working on IE. Now If I keep these two lines, it causes Ajax error, and if not It doesn't work on IE.
Can anyone help?
|
You can't just add arbitrary HTML at the top of a module file - Drupal runs through a process to theme the page, and you need hook into that.
You have a couple of options:
Override html.tpl.php in your theme, and add the tag to the <head> section manually. This is probably the easiest way.
Use drupal_add_html_head() in your module, e.g.
$tag = $element = array(
'#tag' => 'meta',
'#attributes' => array(
'http-equiv' => 'X-UA-Compatible',
'content' => 'IE=edge',
),
);
drupal_add_html_head($tag, 'mymodule:ua_compatibility');
Make sure you pick an appropriate hook to do this in (preprocess_page, etc), don't just add it to the top of the file or it won't work.
| 0.777778 |
Add arbitrary HTML to the top of a module file
|
Logic problem: Atiyah-Macdonald 1.11
|
Proposition 1.11 in Atiyah-Macdonald's "Introduction to commutative algebra" states the following:
"Given an ideal $I$ in a ring $A$ and $p_1, \dots p_n$ prime ideals, then $I \subset \cup_i p_i$ implies that $I\subset p_j$ for some $j\in \{1, \dots, n\}.$ "
This is clearly equivalent to saying that "if $I$ is not a subset of $p_i$ for any $i,$ then $I$ is not a subset of $\cup_i p_i.$"
But they then claim that this last statement is logically equivalent to the following:
"For each $i,$ there exists $x_i \in I$ such that $x_i \notin p_k$ for all $k\neq i.$"
Can anyone help me to see why this statement is logically a consequence of the first? I know this is elementary, but I'm truly stuck and I'm hoping that someone can phrase things in a way that makes them more transparent.
|
The sentence you are citing, "For each $i$, there exists $x_i\in I$ such that $x_i\notin p_k$ for all $k\neq i$", is not the logical negation of the statement, but the application of induction. That is, they assume that the statement is true for $n-1$ prime ideals and are applying to all subsets of size $n-1$ of $\{p_1,\ldots, p_n\}$, i.e., the set of the form $\{p_j\,|\,j\neq i\}$ with $i$between $1$ and $n$
| 0.888889 |
logical negation of statement, but application of induction
|
'Request invitation' doesn't give any feedback of successfully sending
|
I filled the "Request an Invitation" form:
But after submitting, I just got bumped back to the "check your profiles" page without being told whether it worked or not.
If it does work, I may have sent several requests...
|
Looks like Jon got you set. I'm going to go ahead and mark this completed.
| 0.777778 |
Looks like Jon got you set
|
PostgreSQL bytea vs smallint[]
|
I'm looking to import large (100Mb -- 1 GB) multi-channel time-series data into a PostgreSQL database. The data comes from EDF format files that chunks the data into "records" or "epochs" of typically a few seconds each. Each epoch's record holds the signals for each channel of data as sequential arrays of short integers.
I'm mandated to store the files within the database, in the worst case as BLOBs. Given that, I'd like to investigate options that would allow me to do something more with the data within the database, such as facilitating queries based upon the signal data.
My initial plan is to store the data as one row per epoch record. What I'm trying to weigh up is whether to store the actual signal data as bytea or smallint[] (or even smallint[][]) types. Could anyone recommend one over the other? I'm interested in storage and access costs. Usage is likely to be insert once, read occasionally, update never. If one were more easily wrapped up as a custom type such that I could add functions for analysing of comparing records then so much the better.
No doubt I'm low on detail, so feel free to add comments on what you'd like me to clarify.
|
In the absence of any answers I've explored the issue further myself.
It looks like user-defined functions can handle all base types, including bytea and smallint[], so this doesn't affect the choice of representation much.
I tried out several different representations on a PostgreSQL 9.4 server running locally on a Windows 7 laptop with a vanilla configuration. The relations to store that actual signal data were as follows.
Large Object for entire file
CREATE TABLE BlobFile (
eeg_id INTEGER PRIMARY KEY,
eeg_oid OID NOT NULL
);
SMALLINT array per channel
CREATE TABLE EpochChannelArray (
eeg_id INT NOT NULL,
epoch INT NOT NULL,
channel INT,
signal SMALLINT[] NOT NULL,
PRIMARY KEY (eeg_id, epoch, channel)
);
BYTEA per channel in each epoch
CREATE TABLE EpochChannelBytea (
eeg_id INT NOT NULL,
epoch INT NOT NULL,
channel INT,
signal BYTEA NOT NULL,
PRIMARY KEY (eeg_id, epoch, channel)
);
SMALLINT 2D array per epoch
CREATE TABLE EpochArray (
eeg_id INT NOT NULL,
epoch INT NOT NULL,
signals SMALLINT[][] NOT NULL,
PRIMARY KEY (eeg_id, epoch)
);
BYTEA array per epoch
CREATE TABLE EpochBytea (
eeg_id INT NOT NULL,
epoch INT NOT NULL,
signals BYTEA NOT NULL,
PRIMARY KEY (eeg_id, epoch)
);
I then imported a selection of EDF files into each of these relations via Java JDBC and compared the growth in database size after each upload.
The files were:
File A: 2706 epochs of 16 channels, each channel 1024 samples (16385
samples per epoch), 85 MB
File B: 11897 epochs of 18 channels, each channel 1024 samples (18432 samples per epoch), 418 MB
File C: 11746 epochs of 20 channels, each channel 64 to 1024 samples (17088 samples per epoch), 382 MB
In terms of storage cost, here's the size occupied in MB for each case:
Relative to the original file size, Large Objects were about 30-35% larger. By contrast, storing each epoch as either a BYTEA or SMALLINT[][] was less than 10% larger. Storing each channel as a separate tuple give a 40% increase, as either BYTEA or SMALLINT[], so not much worse than storing as a large object.
One thing I hadn't initially appreciated is that "Multidimensional arrays must have matching extents for each dimension" in PostgreSQL. This means that the SMALLINT[][] representation only works when all channels in an epoch have the same number of samples. Hence File C fails to work with the EpochArray relation.
In terms as access costs, I haven't played around with this, but at least in terms of inserting the data initially the fastest representation was EpochBytea and BlobFile, with EpochChannelArray the slowest, taking about 3 times as long as the first two.
| 0.777778 |
Multidimensional arrays have matching extents for each dimension in PostgreSQL
|
Have to set multiple displays on every start
|
I have a HP DV7 with an ATI graphic card and I have a Samsung monitor connected to the laptop. Every time I turn on the laptop the displays are mirrored and I have to go to the Catalyst control centre (Administrative) and change the displays configuration, I have to do this EVERY TIME I turn on the computer.
I Didn’t try the solution suggested here ( Settings for multiple monitors are not stored ) because it took me a lot to make the graphics card work properly and I want to make sure that I have the right solution ( or the "rightest")
Thanks!
|
I had a similar problem which I solved quite easily. Although I've a different video card it might works for you.
I've set an .xprofile file in my home directory with the following content:
xrandr --output LVDS1 --mode 1366x768 --primary
xrandr --output VGA1 --mode 1280x1024 --left-of LVDS1
I think the lines are quite self explaining and you could easily modify it so that it fits your situation. A graphical way to setup your screens using XrandR is ArandR
The settings will be applied when you log in.
| 0.888889 |
How to set .xprofile file in home directory
|
Howto bin series of float values into histogram in Python?
|
I have set of value in float (always less than 0). Which I want to bin into histogram,
i,e. each bar in histogram contain range of value [0,0.150)
The data I have looks like this:
0.000
0.005
0.124
0.000
0.004
0.000
0.111
0.112
Whith my code below I expect to get result that looks like
[0, 0.005) 5
[0.005, 0.011) 0
...etc..
I tried to do do such binning with this code of mine.
But it doesn't seem to work. What's the right way to do it?
#! /usr/bin/env python
import fileinput, math
log2 = math.log(2)
def getBin(x):
return int(math.log(x+1)/log2)
diffCounts = [0] * 5
for line in fileinput.input():
words = line.split()
diff = float(words[0]) * 1000;
diffCounts[ str(getBin(diff)) ] += 1
maxdiff = [i for i, c in enumerate(diffCounts) if c > 0][-1]
print maxdiff
maxBin = max(maxdiff)
for i in range(maxBin+1):
lo = 2**i - 1
hi = 2**(i+1) - 1
binStr = '[' + str(lo) + ',' + str(hi) + ')'
print binStr + '\t' + '\t'.join(map(str, (diffCounts[i])))
~
|
When possible, don't reinvent the wheel. Numpy has everything you need:
#!/usr/bin/env python
import numpy as np
a=np.fromfile(open('file','r'),sep='\n')
# [ 0. 0.005 0.124 0. 0.004 0. 0.111 0.112]
# You can set arbitrary bin edges:
bins=[0,0.150]
hist,bin_edges=np.histogram(a,bins=bins)
# hist: [8]
# bin_edges: [ 0. 0.15]
#Or, if bin is an integer, you can set the number of bins:
bins=4
hist,bin_edges=np.histogram(a,bins=bins)
# hist: [5 0 0 3]
# bin_edges: [ 0. 0.031 0.062 0.093 0.124]
| 0.888889 |
Numpy imports numpy as np a=np.fromfile
|
uniquely rename each of many files using perl
|
I have a folder containing 96 files that I want to rename. The problem is that each file name needs a unique change...not like adding a zero the front of each name or changing extensions. It isn't practical to do a search and replace.
Here's a sample of the names I want to change:
newSEACODI-sww2320H-sww24_07A_CP.9_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07B_CP.10_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07C_CP.11_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07D_CP.12_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07E_R.1_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07F_R.3_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07G_R.4_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07H_R.5_sww2320H_sww2403F.fsa
I'd like to use perl to change the above names to the below names, respectively:
SEACODI_07A_A.2_sww2320H_2403F.fsa
SEACODI_07B_A.4_sww2320H_2403F.fsa
SEACODI_07C_H.1_sww2320H_2403F.fsa
SEACODI_07D_H.3_sww2320H_2403F.fsa
SEACODI_07E_H.6_sww2320H_2403F.fsa
SEACODI_07F_H.7_sww2320H_2403F.fsa
SEACODI_07G_Rb.4_sww2320H_2403F.fsa
SEACODI_07H_Rb.9_sww2320H_2403F.fsa
Can such a thing be done? I have a vague idea that I might make a text file with a list of the new names and call that list @newnames. I would make another array out of the current file names, and call it @oldnames. I'd then do some kind of for loop where each element $i in @oldnames is replaced by the corresponding $i in @newnames.
I don't know how to make an array out of my current file names, though, and so I'm not sure if this vague idea is on the right track. I keep my files with the messed-up names in a directory called 'oldnames'. The below is my attempt to make an array out of the file names in that directory:
#!/usr/bin/perl -w
use strict; use warnings;
my $dir = 'oldnames';
opendir ('oldnames', $dir) or die "cannot open dir $dir: $!";
my @file = readdir 'oldnames';
closedir 'oldnames';
print "@file\n";
The above didn't seem to do anything. I'm lost. Help?
|
Can you do this with rename? It does allow you to use perl code and expressions as arguments if I recall.
The real answer is the one by @chrsblck it does some checks and doesn't make a mess.
For comparison here is a messy one liner that may suffice. It relies on you providing a list of equivalent new file names that will rename your list of old files in the correct order. Perhaps for your situation (where you don't want to do any programmatic transformation of the files names) you could just use a shell loop (see the end of this post) reading lists of new and old names from a file. A better perl solution would be to put both of these file name lists into two columns and then that file using the -a switch , @F and then useFile::Copy to copy the files around.
Anyway, below are some suggestions.
First, set things up:
% vim newfilenames.txt # list new names one per line corresponding to old names.
% wc -l newfilenames.txt # the same number of new names as files in ./oldfiles/
8 newfilenames.txt
% ls -1 oldfiles # 8 files rename these in order to list from newfilenames.txt
newSEACODI-sww2320H-sww24_07A_CP.9_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07B_CP.10_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07C_CP.11_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07D_CP.12_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07E_R.1_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07F_R.3_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07G_R.4_sww2320H_sww2403F.fsa
newSEACODI-sww2320H-sww24_07H_R.5_sww2320H_sww2403F.fsa
With files arranged as above, copy everything over:
perl -MFile::Copy -E 'opendir($dh , oldfiles); @newfiles=`cat newfilenames.txt`; chomp @newfiles; @oldfiles = sort grep(/^.+\..+$/, readdir $dh); END {for $i (0..$#oldfiles){copy("oldfiles/$oldfiles[$i]", "newfiles/$newfiles[$i]"); }}'
Not pretty: you have to grep andsort on @oldfiles to get rid of . .. and put the array elments in order. And there's always the risk that a typo could make a mess and it would be hard to figure out.
If you put the old and new names in a couple of files you could just do this with this with a shell script:
for i in `cat ../oldfilenames.txt` ; do ; done; for n in `cat ../newfilenames.txt`; do cp $i $n;
or just cd into the directory with the old files and do:
mkdir new
for i in * ; do ; done; for n in `cat ../newfilenames.txt`; do cp $i new/$n;
Good luck!
| 1 |
Can you do this with rename?
|
Highcharts - Cannot set x-axes categories in column charts with negative values
|
Hi I have a column chart with negative values which is showing wrong x-axes categories value. I'm sending a pre-build JSON array from the server , but no matter what i can't get the x-axes categories to show the right values.
Here is the code :
var chart_data = JSON.parse(data).avg_range;
console.log(chart_data.x_axes);
var safety_chart_average = {
chart: {
type: 'column',
renderTo: pattern + '-safety-mini-chart-section',
spacingRight: 20,
spacingLeft: 20,
},
rangeSelector: {
enabled: false
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
credits: {
enabled: false
},
title: {
text: "Avg Changes",
marginBottom: -10
},
xAxis: {
categories: chart_data.x_axes
},
series: chart_data.prices
};
This is what i'm getting
The x-axes is showing wrong values, as you can see from the picture above.
But console.log(chart_data.x_axes) gives
["Day 1", "Day 2", "Day 3"] which should be the correct x-axes label.
Please let me know how can i fix this x-axes label error.
|
You are sending in options to a StockChart. If you look in the API for xAxis on StockChart you see that it has no categories.
If you are not using any Highstock functionality I would switch to a regular Highcharts-chart, using new Highcharts.Chart instead.
If you must use Highstock you will have to look into other alternatives, as the xAxis uses time intervals. This StackOverflow answer may give you some hope, depending of how you are using Highstock in your implementation.
| 0.888889 |
You are sending in options to a StockChart
|
When enumerating motivations, is it correct to write firstly, secondly, ..., or first, second, ...?
|
Suppose I am enumerating reasons not to fly. Is it then correct to write/say:
Firstly, I prefer the train because I can see the landscape. Secondly, I have control over my luggage, and thirdly, it is better for the environment.
Or is it rather:
First, I prefer the train because I can see the landscape. Second, I have control over my luggage, and third, it is better for the environment.
I thought the first should be correct, but I find the second one in written texts. Which one is correct?
|
This answer at ELU suggests:
Both are correct, however, there is "overcorrectness" in using firstly because it seems more like an adverb than first.
Go on the length principle: both have the same meaning, but firstly is two characters longer than first. The language will eventually evolve to do without the longer equivalent; I'd use first.
| 1 |
"overcorrectness" in using firstly
|
Why are there so many different types of screws (phillps/flat/hex/star/etc)?
|
Newbie question.
Why is it that there's a bazillion different types of screws? Why can't we just always use one standard screw type? Are there advantages/disadvantages to the different types? Are there times when one type is preferred over another?
Help me understand why there isn't one screw to rule them all.
|
First, I really like Eric's answer for practical reasons. But there is another side to screw head diversity: Security.
In the end, it's usually a temporary measure. Once a company invents a new screw, some third party will start selling tools to remove them. But for a time, any new screw design means the only people who can open your parts are "certified" workshops you've given tools to. Personally I see this a lot in electronic equipment, where the original manufacturer wants some aspect of design kept private or doesn't want after-market mods made to things they sell. Nintendo is particularly active in inventing new screws.
Examples of security screws include 3-prong Torx variants, and Allen heads with a raised dot in the middle of the screw head to stop standard Allen wrenches from fitting.
If you'd like to see a much more industrial version, find a car which has been booted and look at the bolt. I've seen circular bolt heads with an off-center circular hollow inside. No shoulders or slots to grab, you have to have a very specific wrench. And, of course, there are security lug nuts for car tires.
| 1 |
Screw head diversity: Security
|
Force Geoserver SRID 0
|
I'm developing a gis solution which uses only geometry data.
I designed my spatial DB with PostGIS and now I'm performing some trials connecting the DB with GeoServer map server (using the administration page).
In the layer definition of the administration tool there is the mandatory field SRS(Spatial Reference System) to set with the appropriate SRID
I'd like to know which is the default SRID value to set in order to take into account the geometry type. I read that should be 0, but it doesn't work....
Thanks
nico
|
GeoTools (and GeoServer) provide EPSG:404000 for generic 2D systems. Search for GENERIC_2D in http://docs.geotools.org/latest/userguide/library/referencing/crs.html for details.
I've never tried to use it myself but I think it should do what you need.
| 0.777778 |
EPSG:404000 for generic 2D systems
|
IIS 7 email forwarding
|
We have set up an IIS7 box in our company as a hosting server.
Some clients want their email addressed with their domain name forwarded to their respected email addresses (like, [email protected] -> forward -> [email protected]).
How can this be accomplished? it should be for several domains on the server and the mails should be forwarded to various other domains and email providers.
Thanks,
roman
|
If this is a windows hosting platform you need to follow the SPLA guidleines on how a hosted IIS or EMAIl service should be set up. You should have gotten access to that documentation when you signed up for the SPLA license. (it's behind the partner protal or I'd provide the link) SPLA is the ONLY way you can license microsoft products for a hosted environment, luckily it's actually less expensive than buying the actual products. See this link for more details
| 0.888889 |
SPLA is the ONLY way you can license microsoft products for a hosted environment
|
why EF cant translate Int32.Pars(...?
|
why EF cant translate Int32.Parse in Where Condition section?
for example below code has error :
var query = (from list in dbContext.Packages
where list.Id == Int32.Parse(Request["Id"].ToString())
select list).FirstOrDefault();
i solved this problem :
Int32 ID = Int32.Parse(Request["Id"].ToString());
var query = (from list in dbContext.Packages
where list.Id == ID
select list).FirstOrDefault();
|
The way you've solved the problem is correct.
where list.Id == Int32.Parse(Request["Id"].ToString()), if it would work, means to send Request to the database, have the database extract ["Id"], and then call ToString() and Int32.Parse().
Int32 ID = Int32.Parse(Request["Id"].ToString()); is performed on the client. You then get an integer value, and only that integer value is sent to the database.
| 0.888889 |
Where list.Id == Int32.Parse(Request[Id]].ToString())
|
how to plot and animate an hyperbole?
|
I am an new user of Mathematica and learning basics so please guide me
I tried to use this code
Animate[Plot[x^2/a^2 - y^2/b^2 == 1, {x, 0, 2}, {y, 0, 2}],
{a, 1, 3},
{b, 1, 3}]
but I got this error message:
Plot::nonopt: Options expected (instead of {y,0,2}) beyond position 3 in Plot[x^2/FEa$$116^2-y^2/FEb$$116^2==1,{x,0,2},{y,0,2}]. An option must be a rule or a list of rules. >>
All I want to do is to animate a hyperbole with its asymptotes.
|
Animate[ContourPlot[x^2/a^2 - y^2/b^2 == 1, {x, -6, 6}, {y, -6, 6},
PerformanceGoal -> "Quality"], {a, 1, 5}, {b, 1, 5}]
OR
Manipulate[ContourPlot[x^2/a^2 - y^2/b^2 == 1, {x, -6, 6}, {y, -6, 6},
PerformanceGoal -> "Quality"], {a, 1, 5}, {b, 1, 5}]
If you want the plots with the asymptotes, use the following:
Animate[ContourPlot[{x^2/a^2 - y^2/b^2 == 1, a y + b x == 0,
a y - b x == 0}, {x, -5, 5}, {y, -5, 5}, PerformanceGoal -> "Quality"], {a, 1, 5}, {b, 1, 5}]
OR
Manipulate[ContourPlot[{x^2/a^2 - y^2/b^2 == 1, a y + b x == 0,
a y - b x == 0}, {x, -5, 5}, {y, -5, 5}, PerformanceGoal -> "Quality"], {a, 1, 5}, {b, 1, 5}]
| 0.666667 |
Animate[ContourPlot[x2/a2 - y2/b2 == 1,
|
What does "pie" mean in the following sentence?
|
I once saw a sentence:
I will go to a restaurant for pie.
Native speakers didn't correct this sentence. I don't know why. I would say "I will go to a restaurant to eat a pie". But maybe that sentence was right. Could you please explain to me what that (first) sentence means?
|
I will go to a resturant for pie.
There is nothing wrong with this sentence. I imagine the speaker will soon be seated in a restaurant, ordering a slice of pie.
However:
I will go to a resturant to eat a pie.
This is the version that would make me look surprised. When you "eat a pie", that typically means you eat the whole pie.
The same could be said for cake: "eat cake" means "eat some cake", but "eat a cake" means "eat the entire cake."
We don't usually use the word "a" unless a person eats the whole thing as a single unit (in this context, "a" means "one"):
I went to the restaurant and ate a sandwich.
I went to the restaurant and ate a gyro.
I went to the restaurant and ate a salad.
or unless we specify the unit somehow:
I went to the restaurant and ate a bowl of soup.
I went to the restaurant and ate a piece of pie.
I went to the restaurant and ate a rack of ribs.
I went to the restaurant and drank a glass of wine.
But no article is used when there is an unspecified amount of food (the lack of the word "a" means "some"):
When I get to the restaurant, I'll order scrambled eggs.
When I get to the restaurant, I'll order spaghetti.
When I get to the restaurant, I'll order shrimp.
When I get to the restaurant, I'll order pie for dessert.
When I get to the restaurant, I'll get coffee.
Here's something a bit more advanced: The word "the" can be used when referring to a particular restaurant's version of a dish.
What would you like today, sir?
I'll have the veal saltimbocca.
| 1 |
When you "eat a pie", that typically means you eat the whole pie .
|
how to lock object face a certain distance away from another object face?
|
i tried searching for this on google but i came up empty. i want to know how to lock object 2 5 inches away from the corner of object 1? i want it to stay 5 inches away even if i re-scale.
can someone please help me? how do i lock cube 2 5 inches away from the edge of objects 1?
here is an image of what i want to do:
EDIT:
i want to offset "cube 2" 5 inches away from the bottom right vertex of "cube 1" no matter where "cube 1" is?
so if i move or scale "cube 1", "cube 2" would still be offset 5 inches from the bottom right vertex of "cube 1"
|
There are always a few things you can do when trying to move things in exact increments.
the first is to enable increment snapping, noted by the magnet on the bottom of the 3D view-port.
Another way is to type the distance you want your object to move on your keyboard.
example. G>x>1
This will move your object one unit on the 'X' axis.
if you find you object does not line up with the grid Shift+S>'Selection to Grid' will realign your object to the nearest major intersection on the grid.
Hope this helps,
Vince
| 0.777778 |
How to move in exact increments?
|
Javascript pass onclick on child to parent
|
I have div (.upload-drop-zone, yellow zone at screenshot) with another div (.dropzone-width, blue zone) inside.
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div class="dropzone-width">600 PX</div>
</div>
There is a javascript onclick event attached to .upload-drop-zone (when I click on it, it shows file chooser dialog). Event attached by third-party plugin, so I have no access to function which be called.
The problem is that if I make click on .dropzone-width, click event did not pass to .upload-drop-zone so nothing happens instead of showing file chooser dialog. What can I do to fix it?
P.S.: Sorry for bad english.
|
You can listen for a click in the inner div and fire the click on the outer div.
$("#drop-zone-600").click(function (e) {
alert("hey");
});
$("#dzw").click(function (e) {
$("#drop-zone-600").onclick();
});
.upload-drop-zone {
width: 200px;
height: 200px;
border: 1px solid red;
background: darkred;
}
.dropzone-width {
width: 100px;
height: 100px;
border: 1px solid green;
background: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upload-drop-zone dz-clickable" id="drop-zone-600">
<div id ="dzw" class="dropzone-width">600 PX</div>
</div>
Despite the fact that the alert function is inside the click event listener of the #drop-zone-600 div, you can see the alert by clicking any of the divs.
| 0.777778 |
Click event listener of #drop-zone-600
|
Where can I find the duration of a bus trip on Gran Canaria?
|
On 21 December, I will travel by bus from Aeropuerto Gran Canaria via Las Palmas de Gran Canaria to Agaete/Puerto de Las Nieves. I found timetables for buses on Gran Canaria and I found out I need to take line 60 from the airport to Las Palmas and then line 103 from Las Palmas to Agaete. However, I can't find anywhere how long the bus ride takes. Since I'm going to take a ferry, it is important to know the arrival time at the bus stop closest to the ferry terminal at Agaete.
Where can I find more precise timetables for buses on Gran Canaria? Google Transit doesn't know. Is there any other search engine I may use to find arrival times, or, equivalently, the duration of the bus ride?
|
One option appears to be a shuttle, if you would consider that.
It runs from the airport to Agaete, and appears to take 1 hour and 20 minutes.
At the very least, that should help give you an idea of the time it takes.
| 0.666667 |
a shuttle runs from the airport to Agaete
|
Dropbox Webhooks API
|
I want to fetch the events related to my dropbox like I can see here , means I want to get when a particular file is added, changed, moved, deleted or renamed and by which user.
I have looked into the Webhooks docs. The webhook docs states the the response it sends to the callback url contails the userids, with which I can update the directory listing based on the webhook response for the user by calling the /delta.
But with it I cannot tell if there is an operation made for a file like a particular file has been renamed or deleted as since if I rename a file fro abc to xyz. If I get a response then I will look for the changes related to the file xyz which I will not find in my existing database so logically I will be making the events as deleted abc and added xyz, where as the reality is renamed abc to xyz.
It will be really grateful if you can help me regarding this.
|
There's no real way to detect a rename (versus a delete and an add) via the Dropbox API. You can use heuristics (like whether the new file has the same contents as the old file and was created around the same time as the old file was deleted), but those are just going to be guesses with varying levels of accuracy.
Also, there's currently no way via the API to see which user modified a file in a shared folder.
UPDATE: The Core API now includes (in beta) the ability to see who last modified a file in a shared folder. See https://www.dropbox.com/developers/blog/101/new-in-beta-shared-folder-metadata.
| 0.555556 |
No real way to detect a rename via the Dropbox API
|
How to restrict movement for a length or period of time (logic bricks)?
|
How to to restrict the translation (or rotation) in Z axis for a length (yellow line) and activate it after (blue line)? Using only logic bricks.
|
You will need to add a Float property to the 'yellow' area. I called mine "Bar". no reason. (if it isn't area you want to determine it by then skip this step and go with a Delay sensor rather than Collision, Near, or Ray)
Use a Collision, Near, or Ray (depending on your preferences and needs)sensor to determine when the "Bar" property is close enough to invoke the constraint behavior.
Via an And controller, link your sensor to a Constraint actuator and set the axis based on whatever axis is "up" in your diagram. Turn on true level triggering on the sensor.
| 1 |
Float property to the 'yellow' area
|
How to proceed when you are coordinating a project among several research groups and they do not contribute to the progress of the project
|
I am principal investigator in some project that involves other research groups from other countries. When I was writing the proposal, I asked them if they would like to joint the project, and they agreed. I wrote everything, all paperwork, etc. Now, 6 months after the project has been officially started, they are not contributing in any way to the project, only attending project meetings where they talk about their universities, but nothing about the project. I am really annoyed because the situation. From my point of view they should get involved, as my group does. Before asking them directly for the last time in probably in an unpolite way if they will do their assigned part, how would you proceed here?
|
The path to proceed likely depends strongly on four factors:
Does the project have clear and specific milestones in the contract that the collaborators are failing to meet?
Are the others subcontractors to your institution or independently contracted?
What type of oversight is being exerted by the funding agency, and how is the relationship with the responsible program manager?
Are you willing to burn a bridge?
Typically, as lead PI you are responsible for the execution of the entire project, not just your portion, and therefore have a responsibility to your funding agency to appropriately manage your subcontracting collaborators. If the funding agency has instead decided to execute independent contracts to each of the PIs in the grant, then it is largely out of your hands and there is little that you can (or should) do.
Assuming you are lead PI, then if the contract (not the proposal) has requirements in its statement of work that they are not meeting by the given milestone deadlines, then you have much more leverage and a clear case for a "shape up or get defunded" conversation. Similarly, if the funding agency is exerting strong oversight (e.g., in the USA, DARPA often threatens de-funding unless you meet strong milestones by particular frequent deadlines or regularly outperform other research teams; NSF has a much looser oversight process that often just wants to see that something interesting is being accomplished) then you have a strong case that their failure to perform is directly imperiling the whole research project. In either case, as lead PI you have both the right and the responsibility to cancel their funding and redirect it to better accomplish the research tasks that you are being held accountable for.
If the contract doesn't have accountable goals and you aren't being held accountable for their behavior, however, then it is more just a moral offense to you, and you have much less basis on which to legitimately defund your colleagues. Instead, you might look at it as a lesson for the future on writing more specific contracts that can give you the leverage you need to deal with non-performers.
Now if you do defund your colleagues, this has a high likelihood of burning bridges. If you didn't trust them to shape up, why would you want to work with them again? If they feel you defunded them unfairly, why would they want to work with you again?
If the mandate comes from the funding agency program manager rather than you, that may make the defunding somewhat more acceptable by making it "not your fault," but your colleagues may still see it that way. Thus, if the relationship is more important than the money being lost, you may then want to just write this off as a lesson learned and plan more carefully for the future.
In short: there are no easy paths, but which one to walk depends on the balance of relationship value vs. accountability in your contract with your funder and your colleagues.
| 1 |
What type of oversight is being exerted by the funding agency?
|
Why don't banks give access to all your transaction activity?
|
In the era of big data, I find it surprising that banks and credit card companies only offer access to a ridiculously small number of transactions - often only your last 180 days, if that. The longest I've seen was 720 days going back. I suspect they do store everything, but intentionally limit access.
These transactions are text only, take up extremely little space, and storing an individual's lifetime worth of transaction would take less than 10MB of data; about the storage required by two MP3 files, and about 250k records per person per lifetime, if we generously assume everyone makes 10 transactions a day. But I'd be happy with only the last 10 years of transactions, so about 1MB per customer. One of the largest banks, JP Morgan Chase, has ~70MM credit card customers. That means 70TB of data for 10 years of records - hardly impressive for a corporation of that size, with $17B of net income in 2013, when 1TB of cloud storage costs $10 retail per month.
By comparison, would you put up with Gmail or any online email provider keeping only the most recent 120 days worth of email? (And emails do take a lot more space than transactions, are far more numerous, and have to be instantly retrievable.)
Storage requirements for transaction activity are trivial in an era where we're throwing around petabytes and zetabytes.
Is there a sound reason for banks not offering access to all your transactions, other than legacy software on their side?
|
"Things are the way they are because they got that way."
- Gerald Weinberg
Banks have been in business for a very long time. Yet, much of what we take for granted in terms of technology (capabilities, capacity, and cost) are relatively recent developments.
Banks are often stuck on older platforms (mainframe, for instance) where the cost of redundant online storage far exceeds the commodity price consumers take for granted. Similarly, software enhancements that require back-end changes can be more complicated.
Moreover, unless there's a buck (or billion) to be made, banks just tend to move slowly compared to the rest of the business world. Overcoming "but we've always done it that way" is an incredible hurdle in a large, established organization like a bank — and so things don't generally improve without great effort. I've had friends who've worked inside technology divisions at big banks tell me as much.
A smaller bank with less historical technical debt and organizational overhead might be more likely to fix a problem like this, but I doubt the biggest banks lose any sleep over it.
| 1 |
"Things are the way they are," says Gerald Weinberg Banks .
|
How do I make certain areas editable?
|
I'm new to wordpress and I'm currently converting an HTML/CSS site I made to wordpress to make it easier for my client to edit it from the admin panel.
I have provided 3 screenshots and I'll refer to them here.
The first screenshot shows how my website looks so far. It's using a template I made called homepage.php (see screenshot 3 for code). The template includes header.php which contains the logo, navigation menu etc. It has the image banner and finally includes footer.php. I want the "Our Values" part to be editable so that my client can change the text any time they need to.
Currently, they can edit the top part which says "PROtential Coaching" and that's because it's included on the page within the admin panel and not in the template. I want the bottom part including"Our Values" to be editable from that panel too, is there a way to do this or does this content have to be static and within the template? "Our Values" and "Our People" are in a dynamic secondary navigation menu which my client can add items to if they want to, however they can't change the content for the menu item.
Images:
http://imgur.com/yq9y8SQ,5IqOPzr,SHkzrFz
Please help me out guys, I've been looking all over the place for days to get this done.
|
I would recommend installing the Advanced Custom Fields plugin
in order to achieve the desired functionality. Once you download it, create a few fields. For example, create a field called "footer_text" and print it like this:
<?php the_field('footer_text'); ?>
and so on with the rest of the fields.
| 0.777778 |
Install Advanced Custom Fields plugin
|
Why does George Mcfly employ Biff to wax his car after he had previously tried to rape his wife?
|
In Back to the Future, Marty goes back to 1955 and devises a plan for his father George McFly to win over Lorraine in order to ensure Marty's survival.
The plan involved Marty pretending to sexually assault Lorraine then George would step in and stop him. Biff meddles with Marty's plan, by kicking Marty out of the car and then he tries to rape Lorraine. George expecting to find Marty in the car, instead finds Biff and musters the courage to stop Biff and protect Lorraine.
Near the end of the movie when Marty travels back to 1985 we see that Biff is outside of Marty's house waxing George's car. Why would George employ Biff to do this job? I can't imagine Lorraine would be too happy with the idea.
|
It's not clear that Biff was trying to rape Loraine. Although he was clearly taking liberties he should not have.
McFly subdued Biff in the fight at the dance. After that, Biff learned to take his place behind McFly. The car-waxing scene was really just to prove this.
30 years had passed. The new, wiser McFly was undoubtedly able to forgive Biff--especially with Biff in his new subordinate role.
| 0.666667 |
McFly subdued Biff in the fight at the dance
|
What is the best way for a user to select an item by unique identifier?
|
My team and I are building a mobile app where the user will need to input a human-readable unique identifier (the serial number) of a single unit of inventory. Our system tracks the serial numbers that the user can access. We have considered three possible input modes:
1. We show the user the entire list of serial numbers they can access and allow him to select one from the list (like how a select element would work on an HTML page).
Pros:
The user doesn't have to type anything in.
The user can't enter an invalid serial number.
Cons:
The list is likely to be overwhelmingly large.
The serial numbers usually have the same format and are often sequential, so it might be hard to read the list.
Data usage for downloading the entire list of serial numbers
2. We allow the user to start entering the serial number in a text input and have an auto-suggest drop-down with a filtered list of serial numbers the user can access.
Pros:
The user doesn't have to type in a complete serial number.
The user is unlikely to enter an invalid serial number.
Smaller list to choose from than Option 1.
Cons:
The serial numbers usually have the same format and are often sequential, so it might be hard to read the list.
Auto-suggest may have limited value since the unit has a barcode that we could read.
Data usage for downloading a sizable list of serial numbers
3. We require the entire serial number to be entered, and once we recognize the correct number of characters, we validate the serial number against the user's accessible list and show feedback.
Pros:
The unit has a barcode that we could read, so this has the potential to be simpler than an auto-suggest or select-from-list paradigm.
Simpler implementation
Significantly reduced data usage vs. Option 1 and Option 2
Cons:
The unit has multiple barcodes, so it might take a couple of tries for the user to capture the correct one.
Typing manually would be tedious if the camera is unavailable or barcode scanner isn't working for whatever reason (lighting, etc.)
Which of these three is the best approach? Is there a better approach than what we have considered?
|
Well, if you can do this using barcode OR manual input, and you say serial numbers are sequential, so both teh barcode AND teh serial numbers will have common characters, you can do something like this:
1- Offer the user to scan the barcode (include some hint message)
1.1 - If user scans barcode
1.1.1 - on success --> stop
1.1.2 - on failure --> goto 2
2- Offer the user to manually input the value. Here you can ask to enter barcode or SN number. Strip all common elements and ask your user to input the values that are not common.
2.1- If sequentially generated series: ask to enter the last 3, 4, 5 numbers (based on the pattern structure of your serial number)
2.2- If barcode number, you'll have quite some common numbers. For example, on UPC based barcodes, you'll probably need to ask for the last 4 numbers
3- Validate and provide instant feedback
3.1 - If correct, stop process and display success message
--else
3.2 - Ask user to correct input, go to 3
Sorry about the very basic explanation, but hope it's enough to understand the idea
| 1 |
Scan barcode and teh serial numbers have common characters . ask user to manually input the value
|
Where to create a shared media folder?
|
I'd like to place all my family's media in one shared folder for everyone to use from any computer. Whether it's a PC or home server.
What is more appropriate:
Create it in my home folder (/home/lamcro/media/)
Create a new account called media (/home/media/)
or just Create a new folder (/media/)
As far as I know, there is no "Shared Folder" in Ubuntu, like in Windows.
I'm just looking for the least cumbersome method, in case I ever want to do a full Linux re-install.
|
/media: Not such a good idea. You should find an existing folder in that location. This is where Ubuntu auto-mounts any external media. You'll find new folders mysteriously springing up within your share when you plug in some media e.g an external USB drive. You could instead place your files within a folder in /media, e.g /media/Lamcro-Media.
/home/lamcro/media: A so-so choice. Chances of accidental deletion of a folder are high when they are in your home directory. You do not want to lose your photos and home videos due to an accidental click or a command that didn't go as planned.
/home/media: You could do this, if the new user 'media' will own all the files. If not, it'd be just a location, albeit one tied to a user account. I'd avoid this, just because I don't get the logic behind a userid for my media.
My suggestion would be to create a new partition, mount it within /media, e.g. /media/Lamcro-Media and then place your files there. If you ever had to reinstall linux, you would be able to leave this partition untouched, and mount it again on the newly installed system. Failing that, I'd opt for /media/Lamcro-Media as a normal folder, but that's just personal choice.
Going by your question, I'd say the key is to create a new partition to keep all your media. You could then mount it at /media and, if dissatisfied, remount it elsewhere.
| 1 |
/media: A so-so choice.
|
Change top's sorting back to CPU
|
A former coworker did something to top that whenever it runs as root the data is sorted by MEM usage instead of the default CPU usage. According to multiple searches, the man page and even the options within the top console itself (O), just pressing k it should be sorted by CPU, but instead when I hit k it asks me for a pid to kill.
So how can I get back default sorting to CPU?
|
I know it's not a direct answer to your question, but there's a wonderful tool called htop which I'd like to recommend.
It's like an advanced version of the original top tool which allows you to sort the output in a much easier way and appearance.
For example, if you want to sort by CPU, you simply hit F6 and choose your sorting.
Here's how htop looks like:
http://lel.xyz/htop.jpg
Here's how it looks when you press F6:
http://lel.xyz/htopsort.jpg
In order to install it on CentOS/RHEL machines you will have to add the EPEL repo and then simply run:
yum install -y htop
or on Debian machines simply run:
sudo apt-get install htop without adding any repo's.
| 1 |
htop is an advanced version of the original top tool which allows you to sort output by CPU
|
Change Width of Object on Screen Resize
|
How do I use Javascript to change the width of an object when the screen is resized to a smaller width? When the screen is resized back to the bigger size, I want the bigger object.
|
Percentage will make your content to be responsive in smaller screens while resizing the window, while for example 500px will always maintain that same value even though you resize the screen, unless you use media queries. Here's a example, Resize the window where the images are on this link to see it work.
<div class="container">
<div class="responsiveWidth">
...Responsive Image...
<img src="https://s-media-cache-ak0.pinimg.com/736x/0d/0b/7d/0d0b7db51cc6665c0943dc0759f88fa6.jpg" width="500">
</div>
<div class="staticWidth">
...Static Image...
<img src="https://s-media-cache-ak0.pinimg.com/736x/0d/0b/7d/0d0b7db51cc6665c0943dc0759f88fa6.jpg" width="500">
</div>
</div>
and your CSS:
.staticWidth {
width:500px;
margin:10px;
border:1px solid #000;
}
.responsiveWidth {
width:100%;
margin:10px;
border:1px solid #000;
}
.responsiveWidth img{
width:100%;
}
| 0.666667 |
Resize the window where the images are on this link to see it work
|
How to capture Exception in nSpec
|
In my 'act' I want to capture an exception so that I can do multiple tests on the exception data. Examples on the web show how to capture and compare the type/message within a test (or 'It' block) but not how to capture the exception as an 'act' in itself.
I am currently just doing a try/catch within the 'act' body and storing the exception within the context for later testing in the 'It' block. There I can perform a number of different fluent assertions on the data. Is this the best approach?
|
If you're willing to use an open-source framework, you could use Fluent Assertions and do this:
Action act = () => subject.Foo2("Hello");
act.ShouldThrow()
.WithInnerException()
.WithInnerMessage("whatever");
| 0.777778 |
Using an open-source framework, use Fluent Assertions
|
What do you call a group of people that move a lot?
|
I can't think of the word to describe it. Something similar to "wanderer" or "roamer".
It's often used to describe people that don't stay in one place... not "migratory"...
|
I voted up "nomadic" because it is probably the best word to use. However, if we are asking about English as it is commonly used, I have most often heard the word "gypsy" used for that type of person.
The problem is that this is the name of an actual group of people in Europe, and thus the term is somewhat racist. Oddly, it mostly lost its negative connotations here in the USA, but I suspect that isn't the case the closer you get to their homeland in Eastern Europe.
Anyway, if you are talking about an actual culture of people (as it looks like you are), calling them "gypsies" when they aren't actually ethnic gypsies would be very confusing.
| 1 |
"nomadic" is the best word to use .
|
Multiple Threads passing an object reference to static helper method
|
I am just a beginner in Java and have stumbled upon multi-threaded applications. I know this question is similar to some posts here but I couldn't find a better answer for my query. Basically, I want to pass an object to a static method and the method will just return an output based on the values/properties of the object. For every call, I am creating a new instance of the object and there is no chance in any way that I will modify the object inside the method. Now, my question is, will JVM create a new instance of the static method and its local variables into the Stack (excluding the object as it will be on the Heap) for every call by multiple threads? For a clear view of what I want to achieve, here is my code:
TestConcurrent.java
import classes.Player;
public class TestConcurrent
{
private static int method(Player player)
{
int y = (player.getPoints() * 10) + 1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
return ++y;
}
public static void main(String[] args) throws Exception
{
// Create 100 threads
for(int i=1;i<=100;i++)
{
final int j = i;
// Create a new Thread
new Thread()
{
public void run()
{
// Create a new instance of the Player class
Player player = new Player(j,j,"FirstName" + j, "LastName" + j);
// Call static method() and pass a new instance of Player class
System.out.println("Thread " + j + ": " + TestConcurrent.method(player));
// Check the values of the Player class after the call to the static method()
System.out.println("Player" + player.getAcctId() + " : Points=" + player.getPoints() + " Name=" + player.getFirstName() + " " + player.getLastName());
}
}.start();
}
}
}
Player.java
package classes;
public class Player
{
private int acctId, points;
String firstName, lastName;
public Player(int acctId, int points, String firstName, String lastName)
{
this.acctId = acctId;
this.points = points;
this.firstName = firstName;
this.lastName = lastName;
}
public int getAcctId() {
return acctId;
}
public void setAcctId(int acctId) {
this.acctId = acctId;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
OUTPUT:
Since I didn't put a synchronized keyword, the output will be different every time and it looks similar to the following: (output is correct and it is exactly what I am expecting, I just want to clarify that I am on the right path since I don't want to use synchronization as it will slow down the process because each thread will have to wait for the other thread to finish before it can call the static method)
Thread 2: 22
Player8 : Points=8 Name=FirstName8 LastName8
Thread 22: 222
Thread 26: 262
Thread 23: 232
Player23 : Points=23 Name=FirstName23 LastName23
Thread 21: 212
Player21 : Points=21 Name=FirstName21 LastName21
Thread 25: 252
Player25 : Points=25 Name=FirstName25 LastName25
Thread 20: 202
Thread 19: 192
Thread 24: 242
Player24 : Points=24 Name=FirstName24 LastName24
Player9 : Points=9 Name=FirstName9 LastName9
Thread 28: 282
|
will JVM create a new instance of the static method and its local variables into the Stack (excluding the object as it will be on the Heap) for every call by multiple threads?
Yes, that's exactly right.
If a static method only refers to local variables, it is automatically thread safe. (In fact, this holds for non-static methods as well.)
Generally speaking though, I would say you should avoid static if possible. In general it makes code harder to test and to reason about due to the fact that static members are in a sense global.
| 0.888889 |
will JVM create a new instance of the static method and its local variables into the Stack?
|
Huge JSON while saving and returning entity using Hibernate
|
I am using Hibernate to save my entities to database. For simple example I have two entities:
Car:
@Entity
@Table(name = "car")
public class Car implements Serializable {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(cascade = CascadeType.PERSIST)
private List<Wheel> wheelList;
public Car() {
}
public Car(String name, List<Wheel> wheelList) {
this.name = name;
this.wheelList = wheelList;
}
and Wheel:
@Entity
@Table(name = "wheel")
public class Wheel implements Serializable {
@Id
@GeneratedValue
private long id;
private int size;
@ManyToOne(cascade = CascadeType.PERSIST)
private Car car;
public Wheel() {
}
public Wheel(int size, Car car) {
this.size = size;
this.car = car;
}
I am using Spring Framework (MVC) to create REST client, from which I return JSON.
And now: I created simple @Repository and @Service.
I wanted to try if saving works, so I created simple Car object with its wheel list etc. and then, in @Service layer I have persisted it and returned car object into the controller.
Finally, when i run the url from the controller, I recieve HUGE json, because every Car object has wheel list, and then, every wheel has its car, which again has list, and in list are wheels which has cars and so on.. thats why my JSON is so big.
{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":...........
What do i do wrong? How should i solve this problem?
Rest of the code if you need it:(made just for tests, I know about not-well-coded-style here)
Repository:
@Repository
public class TestImpl {
@PersistenceContext
private EntityManager entityManager;
public Car saveCar(Car car){
entityManager.persist(car);
return car;
}
}
Service
@Service
@Transactional
public class TestService {
@Autowired
private TestImpl test;
public Car save(){
Car car = new Car();
car.setName("SomeName");
List<Wheel> list = new ArrayList<Wheel>();
list.add(new Wheel(1, car));
car.setWheelList(list);
test.saveCar(car);
return car;
}
}
Controller:
@Controller
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/los")
@ResponseBody
public Car los(){
return testService.save();
}
}
|
You can add @JsonIgnore annotation to either wheelList field in your Car object or to car field in your Wheel object. This will stop JSON serializer from showing those fields in the resulting document and from recursively including the field.
| 0.777778 |
@JsonIgnore annotation to wheelList field in your Car object
|
What exactly is the difference between Unreal Development Kit and Uunreal Engine 4?
|
I want to start learning game development and I would obviously come across this tool. So every where I went people mentioned Unreal Engine 4 to be a viable choice, I've tried a bit of Unity and now I want to try Unreal. Only issue I came across UDK and UE4, I downloaded UDK which turns out to be different from tutorials and I can't seem to find any info on that and besides I could only run the software once because after the first time it starts a game, I re-installed UDK I still get the issue, but anyways that's a different topic, what I want to know is whether UDK and UE4 are different and if they are, where do i get UE4, becauuse when I down UE4 (from - https://www.unrealengine.com/dashboard), it downloads a game launcher and no development tool. In case they are same, why is my version of UDK different fr
|
You download the Launcher (which is not a game launcher - it's Epic Games Launcher, because the company is called Epic Games), and from within the launcher you can download UE4. This should be trivial to find out though.
| 0.833333 |
Launcher is not a game launcher - it is Epic Games Launcher
|
Simple static integer stack
|
This question is about improving my C++ coding skills. I was asked to implement a simple static integer stack in C++ as an assignment. I've come up with the following code:
class myStaticIntStack
{
int stackSize;
int storedElements;
int *elements;
public:
myStaticIntStack();
myStaticIntStack( int aNumber );
~myStaticIntStack();
int peek();
int pop();
void push( int element );
};
myStaticIntStack::myStaticIntStack()
{
this->stackSize = 1;
this->elements = new int(0);
this->storedElements = 0;
}
myStaticIntStack::myStaticIntStack( int stackSize )
{
this->stackSize = stackSize;
this->elements = new int[ stackSize ];
this->storedElements = 0;
}
myStaticIntStack::~myStaticIntStack()
{
if( this->elements != NULL )
{
if( stackSize > 1 )
delete[] this->elements;
else
delete this->elements;
}
}
void myStaticIntStack::push( int newElement )
{
if( this->storedElements == this->stackSize )
cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
else
{
this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
this->storedElements++;
}
}
int myStaticIntStack::pop()
{
if( this->storedElements == 0 )
{
cout << "Stack is empty, you must PUSH an element before POPping one!" << endl;
return -1;
}
else
{
storedElements--;
return this->elements[ (this->stackSize - 1) - this->storedElements ];
}
}
int myStaticIntStack::peek()
{
if( this->storedElements == 0 )
{
cout << "Stack is empty, you must PUSH an element before PEEKing one!" << endl;
return -1;
}
else
{
return this->elements[ this->stackSize - this->storedElements ];
}
}
int main()
{
myStaticIntStack aStack(3);
cout << "Popped Element: " << aStack.pop() << endl;
aStack.push(1);
cout << "Stack Top is: " << aStack.peek() << endl;
aStack.push(2);
cout << "Stack Top is: " << aStack.peek() << endl;
aStack.push(3);
cout << "Stack Top is: " << aStack.peek() << endl;
aStack.push(4);
cout << "Stack Top is: " << aStack.peek() << endl;
cout << "Popped Element: " << aStack.pop() << endl;
cout << "Stack Top is: " << aStack.peek() << endl;
cout << "Popped Element: " << aStack.pop() << endl;
cout << "Stack Top is: " << aStack.peek() << endl;
cout << "Popped Element: " << aStack.pop() << endl;
cout << "Stack Top is: " << aStack.peek() << endl;
return 0;
}
The code is compiling and running correctly, this is standard output:
Stack is empty, you must PUSH an element before POPping one!
Popped Element: -1
Stack Top is: 1
Stack Top is: 2
Stack Top is: 3
Stack is full, you must POP an element before PUSHing a new one!
Stack Top is: 3
Popped Element: 3
Stack Top is: 2
Popped Element: 2
Stack Top is: 1
Popped Element: 1
Stack is empty, you must PUSH an element before PEEKing one!
Stack Top is: -1
However I was given a B due to the following reasons:
There was a better way of implementing it.
I didn't manage well the case in which I'm trying to POP an element from an empty stack, since it's confusing that pop() returns a value even if Stack is empty.
Can you please help me understand how I could improve my code?
|
this is not always needed in member functions, you can remove all the
this->
The compiler knows this from the context.
And move brackets, e.g.:
int myStaticIntStack::peek() {
if( 0 == storedElements ){
cout << "Stack is empty, you must PUSH an element before PEEKing one!" << endl;
return -1;
}
else{
return elements[stackSize - storedElements ];
}
}
In comparisons, the const is safer on the left. This avoids a possible =, which is a common error.
You could improve it by making a vector class. You may have to do this from scratch if it is homework. It would be better than old C arrays.
| 0.888889 |
How to remove this from the context?
|
What is the best introductory Bayesian statistics textbook?
|
Which is the best introductory textbook for Bayesian statistics?
One book per answer, please.
|
I am now reading : From Algorithm to Z-Scores: Probabilistic and Statistical Modeling in Computer Science by Norm Matloff, UC Davis, freely available for download.
My two cents.
| 1 |
From Algorithm to Z-Scores: Probabilistic and Statistical Modeling in Computer Science
|
Setup ntp client with embedded device
|
I need to run an NTP client on a very limited embedded device.
ntpd is available but I do not see anything like rc.conf, or ntp.conf, or xntp.conf? Can someone advise on how to setup NTP?
I ran ntpd, but the date and time haven't updated.
|
Try ntpd -bq
That will set the time and quit. It will allow you to sync to broadcast servers as well.
That said there are two important things to note. First I don't know who the NTP servers are on you network. If someone is being a bad little techie they could bork your time/date and invalidate some security protocols.
Also be aware that a common problem is that your time is "ahead" of the NTP servers. so when you adjust your time, your files and other things exist in the future. This can really confuse things. Linux doesn't like time travel and it's not afraid to let you know. Normally this is just warnings but can be more serious issues depending on how some scripts are written. I say this because an embedded device usually has some pretty narly scripts on it.
| 0.888889 |
Try ntpd -bq That will set the time and quit
|
How do indirect, session-specific resource tokens increase security?
|
The OWASP web site recommends this:
Use per user or session indirect object references. This prevents attackers from directly targeting unauthorized resources. For example, instead of using the resource’s database key, a drop down list of six resources authorized for the current user could use the numbers 1 to 6 to indicate which value the user selected. [italics mine]
Check access. Each use of a direct object reference from an untrusted source must include an access control check to ensure the user is authorized for the requested object. [italics mine]
So if a user doesn't have access to the requested resource, how does obfuscating the direct object reference improve security?
Given the increased complexity that, say, an ASP.NET MVC site would accrue, is this worth the additional trouble for anything but banking sites?
|
I think you defined a reference object as an absolute and associated with finance. How about the following: You are a software vendor, your sw if sold online after a visitor purchases it. Wouldn't you prefer that ONLY the purchaser be able to access a hyperlink for your product?
Forget the financial (banking sites) or even software, what about say a social network. "Back in the days" if you sniffed the wire, it was a known fact you could pull out the URIs from the tcp capture, open it in a browser, and you had instant access to email, social network components, etc.
There are plenty of different scenarios you'd need it. Think about it for what it is: "Insecure Direct Object" an object directly accessible and cannot be secured for whatever reason. We need to secure it by assigning it a "reference" so it can never be "directly named."
| 1 |
How to define a reference object as an absolute
|
Anybody knows if there is a counterpart for CTR+w , that deletes immediate words after cursor
|
I mean when the cursor is on the left side of the words ,I would like to remove the words on the immediate right side of it . CTR+k remove everything on the right side, i only want one word to be removed.
|
Bash tends to use libreadline for commandline input, so you can create an inputrc file that lets you control what keystrokes do what. man readline 3 should explain the format, you can also find this in the READLINE section of bash's manpage (the specific command you want is kill-word)
zsh doesn't use libreadline apparently, but it seems they've mimicked a lot of the functionality. It looks like there are some options to mimic bash's word matching, but you'll need to bind them to a key.
| 0.888889 |
zsh uses libreadline for commandline input .
|
What should I do with comments that need to be edited?
|
I have reputation 521, I can edit question and answer but not a comment. There is very helpful, but mistyped comment. Only one letter need to be changed. Should I flag it? I have no right do anything else.
Let us see the example:
There is a question:
Where is @Html.MailTo in MVC 4?
And the most usefull part of the answer for me is the comment: "marked up with a helper attribute e.g. [DataType(DataTypes.EmailAddress)]"
But it should be DataType.EmailAddress instead of DataTypes.EmailAddress.
I would like to delete the mistyped s, but I cannot. What should I do?
|
In this situation you edit it into the answer.
If the answer is incorrect and corrected in a comment, which is itself incorrect then correcting the comment seems more than a little ridiculous. Add all the information into the answer instead and everything's in one place.
Be careful doing this. People sometimes don't like editing of code. Ensure that your edit summary states that you're moving useful information from a comment into the post and I would link to the documentation that proves you're correct. I know nothing about the subject so I'm not making the edit myself.
Don't be upset if your edit gets rejected. If it does all shrug your shoulders and move on; it's only an "s" after all; you'd hope people would work it out if they copied and pasted the code and got an error.
If your edit is approved you can flag all the comments as obsolete and help keep the place that little bit cleaner.
| 1 |
Editing a comment into the answer
|
What conditions may cause "The content on this page has either been modified by another user..."?
|
I'm working on a website which has multiple admins, some creating contents, some editing and some tagging...
I know editing one node at the same time will cause this error, is there anything else cause this error?
The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.
|
I just managed to create this error with a FireFox setting. I told FF never to save history and cleared my browser cache and then could not submit changes to nodes. When I turned 'save history' back on, the issue resolved. Probably related to a change in how FF was handling cookies.
Site is Drupal 7 with OpenPublish, IDK much more than that as I'm new to the project.
| 1 |
FireFox setting
|
Photons and Relativity
|
Consider a Photon from Sun and travels with a velocity $c$. Now think we are that photon. For us, it looks like Sun is moving away from us with a velocity $c$. So, why don't we get attracted back towards Sun, because the mass of Sun would be infinite for us since it moves away from us with a velocity $c$.
|
When anything moves at the speed of light, all of our physical models break down. If you were to watch a spaceship speed up to the speed of light, you would see a clock on the ship slow down and come to a complete stop when it hit the speed of light (assuming you could even see it at this point). The ship would also contract so much in the direction of motion that it would become infinitesimally small and, when it hit c, it's length would hit zero. As a result, matter cannot ever reach the speed of light (as far as we know).
It is a common misconception that mass changes when you travel at relativistic speeds, but this is not actually the case. The kinetic energy of an object increases relativistically, but the physical mass of the object (and, therefore it's gravitational effect on surrounding spacetime) does not actually change.
By our current notion of relativity, it is completely possible that there exists another universe within our own, in which photons are at rest and we are moving at 3e8 m/s and have energy but no other way of interacting with the type of "matter" that exists here. Our world is inaccessible to this one and vice-versa. There could be completely different laws of physics in this parallel universe, we have no idea because it exists (or doesn't) in a singularity.
| 0.888889 |
When anything moves at the speed of light, all of our physical models break down .
|
Index "server_name" not exist
|
I try to execute a bat, and in this file i try to acceed to this variable :
$_SERVER['SERVER_NAME']
But it doesn't exist this index. In fact, when i try to print_r($_SERVER), there is no SERVER_NAME index. There is a reason ? Is it because i launch this function in a bat ?
Have I an other solution for get this variable ?
Thank you !
|
The $_SERVER variables are only available in a server environment (hosting PHP through Apache or another web server), so if you are launching it from the command line they won't be available. The parameters of this object are populated by the HTTP headers, which in your case don't exist.
If you want to ignore the $_SERVER object when the SERVER_NAME isn't set, you can alternative use php_uname("n") but your mileage may vary depending on operating system.
$server_name = (isset($_SERVER['SERVER_NAME']))? // check if SERVER_NAME is set
$_SERVER['SERVER_NAME'] : // if yes, use HTTP header value
php_uname("n"); // if no, use php_uname()
| 0.888889 |
$_SERVER variables are only available in a server environment
|
How do I make an endless road in Unity?
|
Basically I created 2 quads side by side and I added a road texture. I used transform.translate so that the road moves, but I am trying to make the road endless by making the 2 quads reposition themselves in front of the current quads repeatedly so that when I add a player the road is endless. Any way I could do this?
|
Well, the answer of Vinayak Garg is good but since you work with perspective this won't be perfect. This is basically paralax mapping and works great for 2D games. But here you want to have the road dissapear in the horizon probably. If your road is straight then just extent on this technique and add many pieces until it is looking good. Whenever you leave a piece behind move it to the front.
If you want a curvy rode you have to look in procedural algorithms to generate a path for you can use pieces to correct this path. Perlin noise for example can be used for "infinite" randomization. They use it for minecraft in 3D, you just probably just need a 1D variant that just controls the the curve of the road. ANyway, this is a lot harder to implement.
| 1 |
Paralax mapping for 2D games
|
What is a "strictly positive distribution"?
|
I am reading Judea Pearl's "Causality" (second edition 2009) and in section 1.1.5 Conditional Independence and Graphoids, he states:
The following is a (partial) list of properties satisfied by the
conditional independence relation (X_||_Y | Z).
Symmetry: (X_||_ Y | Z) ==> (Y_||_X | Z).
Decomposition: (X_||_ YW | Z) ==> (X_||_Y | Z).
Weak union: (X_||_ YW | Z) ==> (X_||_Y | ZW).
Contraction: (X_||_ Y | Z) & (X_||_ W | ZY) ==> (X_||_ YW | Z).
Intersection: (X_||_ W | ZY) & (X_||_ Y | ZW) (X_||_ YW | Z).
(Intersection is valid in strictly positive probability distributions.)
(formula (1.28) given earlier in the publicatiob: [(X_||_ Y | Z) iff P(X | Y,Z ) = P(X | Z) )
But what is an "strictly positive distribution" in general terms, and what distinguishes a "strictly positive distribution" form a distribution that is not strictly positive?
|
As an example illustrating the definition of a strictly positive probability distribution in action (Courtesy of an old paper by Richard Holley on FKG Inequalities), imagine that we have $\Lambda$ which is a finite fixed set. Imagine also that we have $\Gamma$, which is a sublattice of the lattice of subsets of $\Lambda$. Let us then let $\mu$ be a strictly positive probability distribution on some finite distributed lattice $\Gamma$. For $\mu$ to be strictly positive, $\mu(A)>0$ for all $A\in\Gamma$ and $\sum_{A\in\Gamma}\mu(A)=1$
| 0.555556 |
a strictly positive probability distribution in action
|
How do I burn a DVD with more than 3.8 GB data?
|
I use Kubuntu 12.04 with KDE 4.8.3 and wodim / genisoimage 1.1.11, but the problem is on Ubuntu (with Brasero) and occurred in Oneiric as well.
Whenever I try to burn more than 3.8GB (approaching the 4 GB limit) of data onto a DVD, burning fails, aborts, or gives an "error 254."
I have lost more than 50 DVDs this way until I learned about the 3.8GB limit. Anything under 3.8GB burns fine, and DVDs burned with more than 3.8GB have usable data up to 3.8 GB, but then the remaining data is garbled, unaccessible, or the disk is just not recognized.
I'm pretty certain this is related to the replacement of cdrecord / mkisofs with wodim /genioimage (which is a problem that has been described for years). Is there another answer or fix? Re-installing cdrtools/cdrecord/mkisofs in Oneiric and Precise has become a herculean task.
|
Try other programs, i.e. gnomebaker or simpleburn:
http://simpleburn.tuxfamily.org/ -- https://launchpad.net/~simpleburn/+archive/ppa
http://sourceforge.net/projects/gnomebaker/ -- https://launchpad.net/~gnomebaker/+archive/stable
There are different types of DVDs that support different capacities. According to the wikipedia article (Capacity and nomenclature of (re)writable discs), there are two versions of DVD-R discs, ~3.68 GiB and ~4.37GiB (Don't look at GB, but GiB, that's the actual data capacity).
Always look at what's printed on the DVD, they usually mention if they're DVD-R or DVD+R. If they don't mention anything (i.e. no-named), don't buy them, unless you're up for the risk.
Prefer DVD+R (no specific reason, but if you need one, they don't have 2 versions and are 4.37 GiB in capacity).
You could also try the dual layered dvds, which provide ~8 GiB in capacity.
For testing purposes buy 2-3 DVD+RW discs.
Burn at low speeds, 4x recommended.
Devices such as dvd burners die eventually (at least in my case), after 2-3 years they become faulty. For example, burning worked in my case, except that I couldn't boot using any cd/dvd media. I bought a new CD/DVD burner and recycled the old one. Now the new one after 2 years burns only at speeds lower than 10x. Go figure. :)
| 0.888889 |
Different types of DVDs that support different capacities
|
How to enable or disable services?
|
I read about how to enable and disable services in Ubuntu and it seems that there are different possibilities to manage them.
The first method I found is update-rc.d to add new services to startup, which aims on the /etc/init.d folder and its contents.
The other one I found is to edit .conf files in the /etc/init folder.
What's the recommended way to enable / disable / add services and why?
Could you please give a short bulletproof step by step example on how to add a service in Ubuntu and enable and disable it?
|
Currently there are actually 2 different ways for software to be started as a service in Ubuntu. A service is defined here as a program run by the system in the background, as opposed to one started and run directly by the user.
The traditional way to start services in Linux was to place a script in /etc/init.d, and then use the update-rc.d command (or in RedHat based distros, chkconfig) to enable/disable it. This command, btw, uses some mildly complicated logic to create symlinks in /etc/rc#.d, that control the order of starting services. If you run ls /etc/rc2.d you can see the order that services will be killed (K##xxxx) and started (S##xxxx).
The issue with that was that when booting the system, everything had to be done in serial, one thing after another, making system boot times really slow. Attempts were made to parallelize this, but they were haphazard and hard to take full advantage of. This was the main reason that Upstart was created.
Upstart uses job definition files in /etc/init to define on what events a service should be started. So, while the system is booting, upstart processes various events, and then can start multiple services in parallel. This allows them to fully utilize the resources of the system, for instance, by starting a disk-bound service up while another CPU-bound service runs, or while the network is waiting for a dynamic IP address to be assigned.
You can see all of the upstart job files by running ls /etc/init/*.conf
Let me just stop here and say that if you don't know what a service is, or what it does, DO NOT disable it!
Not all services have been converted to upstart. While working on the server team at Canonical for the past few months, I've worked on a number of converted job files, and the nicest part is that it allows one to get rid of all the script "magic" and just put in a few commands here and there to define exactly how to start the service, and nothing more. But for now, only a handful of traditional network services, like squid and samba, have been converted.
In order to figure out if a service is upstart based, you can run the status command:
status servicename
If its an upstart job, it will show this:
$ status statd
statd start/running, process 942
But if its not, you'll see something more like this:
$ status apache2
status: Unknown job: apache2
In this case, apache2 has not been converted to upstart. So, to disable apache2 you just run
sudo update-rc.d apache2 disable
sudo service apache2 stop
Upstart job definitions do not have an update-rc.d command. To disable the job, you need to edit the job file directly to disable it. There are two ways to do this.
If you want to still be able to manually start it, then you need to comment out the 'start on' condition. Say you want to install samba, but not have it start automatically.. here is its job file (in natty):
description "SMB/CIFS File Server"
author "Steve Langasek <[email protected]>"
start on local-filesystems
stop on runlevel [!2345]
respawn
pre-start script
RUN_MODE="daemons"
[ -r /etc/default/samba ] && . /etc/default/samba
[ "$RUN_MODE" = inetd ] && { stop; exit 0; }
install -o root -g root -m 755 -d /var/run/samba
end script
exec smbd -F
To disable it, you can just put a # in front of the 'start on local-filesystems'. Note that while it won't start back up on boot, you still need to stop it this time with
sudo service smbd stop
If, however, you never want it to start, I'd suggest actually removing the package. If, however, you want it installed, but not startable, you can also do:
mv /etc/init/smbd.conf /etc/init/smbd.conf.disabled
Starting with the version of upstart that will be in 11.04, there is a new keyword that disables the 'start on' and 'stop on' stanzas, it is 'manual'. So another way to disable the service as of 11.04 is to do:
command using sudo
echo 'manual' | sudo tee /etc/init/mysql.override
command from root shell
echo manual >> /etc/init/mysql.override
And, hopefully real soon, you will be able to create an "override" file to disable a service without editing the job definition at all, by just putting the 'manual' keyword in it.
| 0.777778 |
How to start a service in Ubuntu
|
Protractor test vs long-polling
|
I have an Angular web app that continuously listens for notifications from the backend via long-poll:
scope.notification = $resource('/notification').get();
This request never completes in the test environment. This is a problem for Protractor, because it wants to wait for all outstanding HTTP requests to finish.
I see a number of potential solutions, but have some issues with all of them.
I do not see a way to tell Protractor to ignore this request. Issuing it from $interval (which itself is ignored) is not a solution. Protractor will not wait for the request to be sent, but once it's sent, it will still wait for it to complete.
So I'm trying not to send this request when running the tests. But how do I know I'm in a test?
I could add a flag to the URL (?protractor=true). But my web app modifies the URL all the time, so it would get cleared quickly.
I tried setting a variable: browser.executeScript('window.runningProtractorTests = true;'); But it seems Protractor will wait for the page to sync first before running executeScript. And I'm sending the request right away when the page loads.
I could set a cookie. But it's fairly cumbersome, e.g. I'd have to load the page twice. (See issue 341 for more difficulties.)
I could set a user agent. It's not easy either. I would need to set browser flags for each browser in the config file. I do not want to completely override the user agent (to Protractor, for example) out of fear that my libraries may rely on interpreting the user agent string, so I'd have to figure out the right string.
I could check if the server is running on a specific port. But then a year from now someone will try to run the production server on the same port and not understand why the notifications don't work.
Making the test backend complete the request immediately does not help, because it's immediately sent again whenever it completes. But I guess I could introduce a special "you are in a test" notification and stop the polling when this is received. This would mean a (small) change to our protocol, so I'd rather avoid it if possible.
Is there no straightforward way to do this?
|
Try to load the view with browser.driver.get('http://myapp'). Calling the webdriver api directly will not wait for angular to be ready.
Then you can run the script.
browser.driver.executeScript('window.runningProtractorTests = true;');
And then continue using the protractor api.
You may have to add a browser.waitForAngular() to make sure that angular is ready before proceeding with your test.
| 1 |
Calling the webdriver api directly will not wait for angular to be ready
|
Will dismissal from one graduate school affect me applying to another?
|
I was dismissed from my Masters program due to bad grades. I also have a mention in my records that say that I might have used last years homework. I did not copy and they had no proof that I copied per se. I couldn't care less about my grades at the time and I deeply regret doing what I did. Is there hope for me in applying to grad schools in the future?
Additionally, I am an international student. Can someone tell me if all this will affect my getting a VISA?
|
Unfortunately, your transcripts are likely going to be required at time of application to any other program, and you can assume that you will be asked about your poor grades during the application process. That said, you're not the first person to have made bad decisions in the past, so I would definitely still apply.
One thing I would strongly advise not doing is attempting to hide the fact you have poor grades by simply not sending the transcript, and pretending it didn't happen. Doing so will almost guarantee career-threatening problems later on when someone finds out what you did (and it won't be hard, there will be a gap of a few years you won't be able to explain, and all the officials at the other university still know that you were there).
I have no idea about the visa.
| 0.888889 |
Doing so will almost guarantee career-threatening problems later on when someone finds out what you did
|
Can a PC have more than one Default Gateway?
|
I know that a PC can have multiple network adapters each of which with different network identifiers (IP,MAC etc.).
My question is, can a certain PC have more than one active default gateway? And if so, how does the PC (or better say the OS) knows to what adapter use for any given packet?
|
If your server/PC is multihomed, meaning it is part of two separate networks, you would have a default gateway on each network adapter. You then prioritize the network adapters. Like others have said though, you still just have one default gateway, but it's per network adapter.
| 0.888889 |
Default gateway on each network adapter
|
Derivative of Continuous and Differentiable Piecewise function is indeterminate
|
I'm attempting to analytically stitch together two linear functions with two quadratic functions. The function I'm considering, then, is a piecewise function consisting of 4 parts. Below are the values I'm considering for the scenario as well as the function itself.
k1 = 1.41; k2 = 1.45; eps1 = 2*^8; eps2 = 3.5*^8; p0 = 1.04*^8; delP = 0.01*^8;
kmax = (1/2)(k1 + k2) + (k2 p0 + eps2 - k1 p0 - eps1)/delP;
edens[p_] := Piecewise[{{k1 p + eps1, p <= p0 - delP},
{(1/2)(kmax - k1)/delP * (p-p0)^2 + kmax(p-p0) + (k1 p0 + eps1) + (1/2)delP * (kmax - k1), p0-delP <= p <= p0},
{(1/2)(k2 - kmax)/delP * (p-p0)^2 + kmax(p-p0) + (k2 p0 + eps2) + (1/2)delP * (k2 - kmax), p0 <= p <= p0+delP},
{k2 p + eps2, p >= p0 + delP}}];
This function is continuous and differentiable at the boundary points, which you can see by plotting it:
Plot[edens[p], {p, p0 - 2*delP, p0 + 2*delP}, Exclusions -> None]
However, if I try and evaluate the derivative of this function at the boundary points (p0, p0-delP, and p0+delP), I get Indeterminate even though the value is the same on both sides.
I have a feeling this is because I'm using approximate real numbers. Is there anyway to force Mathematica to say that the derivative at a boundary point is a specific value?
|
You may define:
deriv[fun_, pp_] := Limit[D[fun[p], p], p -> pp]
deriv[edens, p0]
(* 155.59 *)
In fact, this way you can also obtain a symbolic form for the derivative
Clear[k1, k2, eps1, eps2, p0, delP, kmax];
deriv[edens, p] // InputForm
(* Piecewise[{{k1, delP + p - p0 <= 0},
{kmax + ((-k1 + kmax)*(p - p0))/delP, delP + p - p0 >= 0 && p - p0 <= 0},
{kmax + ((k2 - kmax)*(p - p0))/delP, p - p0 >= 0 && delP - p + p0 >= 0},
{k2, delP - p + p0 <= 0}},
0] *)
To get a plot you could use:
Plot[deriv[edens, p] /. p -> pp, {pp, p0 - 2*delP, p0 + 2*delP}, Exclusions -> None]
| 0.888889 |
Deriv[edens, p0] // InputForm
|
Online broker available in Europe - to buy index funds or ETF with small investments
|
So i am trying to start investing periodically some small amounts.
I am particularly interested in index funds or ETF.
I would like to be able buy, track, sell them, and etc online.
There are a lot of online brokers like : TD Ameritrade, etrade and etc. , but i cant seem to find the one that would allow to register fro Europe citizen, like from Denmark. (all the top ones require USA citizenship or etc).
Is there any like that at all ? If not - what other options there are to make such investments ?
|
A few ideas to get you started
Go to your newsagent and buy the latest issue of some DIY investing magazine. You should get some commercial on the major players
DumbCoder suggested tdwaterhouse. They have an offshore service (never tried them but the fees look high)
Saxobank has a strong presence in the nordics
Check this page. They seems to be comparing brokers in the different European countries. Not sure what to think about that their results. If I check for the UK I notice that a lot of the big guys are missing
Use Google
| 1 |
How to get started with a DIY investing magazine
|
Killing child thread from parent thread in java
|
I am working in java android platform. I am creating a child thread from main thread. I want to stop child thread as my requirments. My child thread has simple function which doesn't have any loop. I want to kill child thread and free resources it is using, whenever I want. I searched for it and I found inturrupt() function.my thread is:
public class childThread implements Runnable{
public void run() {
firstFunction();
secondFunction();
}
}
Main thread has this code to start above thread:
Thread tChild;
tChild = new Thread(new childThread(), "Child Thread");
tChild.start();
my run() function is calling function like this. How to I use inturrupt() in this? Please tell me any other way to kill child thread and deallocating its resources. Thank you.
|
Just call interrupt on tChild object and it will interrupt your child thread
Thread tChild;
tChild = new Thread(new childThread(), "Child Thread");
tChild.start();
//...
tChild.interrupt();
| 0.888889 |
interrupt on tChild object
|
Tools to run a background process command line in windows?
|
In linux we just need to append a & and that's all.
What for windows?
|
start /min cmd /c mycommand
If you want to run other jobs in the same shell you have to use powershell background jobs
If you want to hide the command window save a vbscript file with the following code(replacing the commands as needed) :
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\mycommand_path\mycommand and args" & Chr(34), 0
Set WshShell = Nothing
create a shortcut to this file and run this from the shell directly by double clicking it. It sounds like what you are really after is job control. Install the subsystem for unix to get the bash or ksh prompt and execute it from there if you want job control however it would not suprise me if running it as a background job causes issues. You will probably want to run it as a background process instead.
| 0.666667 |
Install a subsystem to get the bash or ksh prompt and execute it from there
|
Combining two fields in SELECT statement
|
In my table I have a field "firstname" and a field "lastname". I would like to select all records where firstname + space + lastname is a certain value.
I've tried this:
$sql = "SELECT * FROM sam_users WHERE (user_firstname + ' ' + user_lastname LIKE ?)";
But this isn't working. With Google I've found something about using ||, but I don't really understand how I should use that operator. Note that I don't want to use an or-operator (what || is in many languages), but something to concatenate 2 fields (with a space between them) and using a LIKE on that.
Thanks!
|
With MySQL, you can use CONCAT:
SELECT * FROM sam_users
WHERE CONCAT(user_firstname, ' ', user_lastname) LIKE ?
or CONCAT_WS (which ignores NULL values):
SELECT * FROM sam_users
WHERE CONCAT_WS(' ', user_firstname, user_lastname) LIKE ?
However, MySQL won't be able to use any indices when performing this query. If the value of the pattern argument to LIKE begins with a wildcard, MySQL won't be able to use indices, so comparing to a generated value (instead of a column) won't make a difference.
You can also set the MySQL server SQL mode to "ANSI" or "PIPES_AS_CONCAT" to use the || operator for string concatenation.
SET @@sql_mode=CONCAT_WS(',', @@sql_mode, 'PIPES_AS_CONCAT');
SELECT * FROM sam_users
WHERE (user_firstname || ' ' || user_lastname) LIKE ?
This sets the SQL mode for the current session only. You'll need to set @@sql_mode each time you connect. If you wish to unset 'PIPES_AS_CONCAT' mode in a session:
SET @@sql_mode=REPLACE(@@sql_mode, 'PIPES_AS_CONCAT', '');
MySQL appears to remove any extra commas in @@sql_mode, so you don't need to worry about them.
Don't use SELECT *; select only the columns you need.
| 0.888889 |
SELECT * FROM sam_users WHERE CONCAT(user_firstname, ' ', user_
|
Magento (1.7) Bundled Product with FREE Product Option
|
I'm looking to create a bundle offer where customers can buy two items from a collection (30 products with varying prices) and they get a fixed third item which is a FREE product.
As the final price will vary depending on what the customer chooses, how do I make the basket subtotal add the two items but ignore the third priced item?
Hope that makes sense
|
Since the third item is fixed, you can use shopping cart price rules:
if cart contains at least two items of category X
then add product Y as a gift
However you need a small extension for the "add product as a gift" action in shopping cart price rules:
You can get it for free here: https://github.com/code4business/freeproduct
(Disclaimer: I was involved in the development of this extension)
| 0.888889 |
Add product as a gift in shopping cart price rules
|
Trouble getting PythonAnywhere to scrape web for me
|
I've been experimenting around on PythonAnywhere trying to get some python to work on a webserver. I initially switched from Arvixe because they were running 2.4 and PythonAnywhere's name was just too appealing.
My application consists of two files: phones.py and phonesearch.py. Together they are supposed to scrape craigslist for phone prices.
I test locally in 2.7 and it runs just fine, generating an html page (celly.html) with a table and all of the prices. When I upload it, it generates the html just fine, but refuses to to add anything to my prices list ([intprices]).
My suspicions: (a) because it works fine locally, PythonAnywhere isn't allowing it to communicate with craigslist; or (b) because I'm doing this like a caveman and not using a microframework, PythonAnywhere is denying me; or (c) I am blind to my errors and I have missed something obvious.
My python scripts are located in /home/tseymour/mysite and the html is generated at same/mysite/static/celly.html. The file is served up at http://tseymour.pythonanywhere.com/static/celly.html
You'll notice that all of my cells are filled with "N/A" which means it raised an IndexError in the try:" in SearchPhone.py. This means my lists are being filled!
But WHY is that?! I believe it is because I am PythonAnywhere n00b.
Please advise.
SearchPhone.py
from BeautifulSoup import BeautifulSoup
import urllib
import re
def SearchPhone(phone):
y = "http://losangeles.craigslist.org/search/moa?query=" + phone + "+-%22buy%22+-%22fix%22+-%22unlock%22+-%22broken%22+-%22cracked%22+-%22parts%22&srchType=T&minAsk=&maxAsk="
site = urllib.urlopen(y)
html = site.read()
site.close()
soup = BeautifulSoup(html)
prices = soup.findAll("span", {"class":"itempp"})
prices = [str(j).strip('<span class="itempp"> $</span>') for j in prices]
for k in prices[:]:
if k == '': #left price blank
prices.remove(k)
elif int(k) <= 75: #less than $50: probably a service (or not true)
prices.remove(k)
elif int(k) >= 999: #probably not true
prices.remove(k)
#Find Average Price
intprices = []
newprices = prices[:]
total = 0
for k in newprices:
total += int(k)
intprices.append(int(k))
intprices = sorted(intprices)
try:
del intprices[0]
del intprices[-1]
avg = total/len(newprices)
low = intprices[0]
high = intprices[-1]
if len(intprices) % 2 == 1:
median = intprices[(len(intprices)+1)/2-1]
else:
lower = intprices[len(intprices)/2-1]
upper = intprices[len(intprices)/2]
median = (float(lower + upper)) / 2
namestr = str(phone)
medstr = "Median: $" + str(median)
avgstr = "Average: $" + str(avg)
lowstr = "Low: $" + str(intprices[0])
highstr = "High: $" + str(intprices[-1])
samplestr = "# of samples: " + str(len(intprices))
linestr = "-------------------------------"
except IndexError:
namestr = str(phone)
medstr = "N/A"
avgstr = "N/A"
lowstr = "N/A"
highstr = "N/A"
samplestr = "N/A"
linestr = "-------------------------------"
return (namestr, medstr, avgstr, lowstr, highstr, samplestr, linestr)
phones.py
from SearchPhone import SearchPhone
phones = ["Iphone 4", "Iphone 5","Galaxy s3", "Galaxy s2", "LG Lucid", "LG Esteem", "HTC One S", "Droid 4",
"Droid RAZR MAXX", "HTC EVO", "Galaxy Nexus", "LG Optimus 2", "LG Ignite",
"Galaxy Note", "HTC Amaze", "HTC Rezound", "HTC Vivid", "HTC Rhyme", "Motorola Photon",
"Motorola Milestone", "myTouch slide", "HTC Status", "Droid 3", "HTC Evo 3d", "HTC Wildfire",
"LG Optimus 3d", "HTC ThunderBolt", "Incredible 2", "Kyocera Echo", "Galaxy S 4g",
"HTC Inspire", "LG Optimus 2x", "Samsung Gem", "HTC Evo Shift", "Nexus S", "LG Axis", "Droid 2",
"G2", "Droid x", "Droid Incredible"
]
f = open('/home/tseymour/mysite/static/celly.html','w')
f.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Celly Blue Book</title>
</head>
<body>
</body>
</html>
""")
#table
f.write('<table width="100%" border="1">')
for x in phones:
print "SEarchphone0"
y = SearchPhone(x)
print "SEarchphone"
f.write( "\t<tr>")
f.write( "\t\t<td>" + str(y[0]) + "</td>")
f.write( "\t\t<td>" + str(y[1]) + "</td>")
f.write( "\t\t<td>" + str(y[2]) + "</td>")
f.write( "\t\t<td>" + str(y[3]) + "</td>")
f.write( "\t\t<td>" + str(y[4]) + "</td>")
f.write( "\t</tr>")
f.write('</table>')
f.close()
Also, I did upload beautifulsoup just incase
|
PythonAnywhere dev here. You don't say if you're using a free or a paid PythonAnywhere account, but if it's a free one then I think you're running into our whitelist. For free accounts, we only allow access to a particular set of websites -- this is because people were using us to do Bad Things.
We put sites on the whitelist so that free accounts can use them if they have an official publicly-accessible API, and unfortunately Craigslist doesn't have one -- quite the opposite, unfortunately.
If you sign up for a paid account then you'll probably be able to do what you want, but if the article I just linked to is correct then you might want to make sure you have good lawyers...
| 0.777778 |
Free or paid PythonAnywhere accounts only allow access to a specific set of websites .
|
"Hirable" or "hireable"
|
What is the correct adjective form of the word hire? I have seen references to both hireable and hirable.
I checked using Google's Ngram viewer book search and it appears that both have been in use since the 1800s with hirable becoming a bit more popular in the past decade or so:
|
Languages evolve, Americans spell and pronounce words differently to British. To me hireable looks less likely to have the word mispronounced. Hireable without an e looks problematic as without the e after the first r the I sound has several options. Possibly a short I sound ?
| 1 |
Hireable without an e looks problematic as without the e
|
Oracle.DataAccess.Client.BulkCopy - trying to cast varchar2 as number when it shouldn't
|
I have a table (A) that includes a column named confirmation_number. It is defined as a varchar2(30) and contains something like SMITERI-2012-02-31-4567.
I have another table (B) that also includes a column named confirmation_number, and it is also a varchar2(30).
I have a stored procedure that extracts the data from A, performing some transformation on it, and it includes the confirmation number column.
I use C# and ODP.Net to run the stored procedure and load a DataTable with it. I then perform some additional transformations. However, I never touch the confirmation number column.
Finally, I create an OracleBulkCopy object, set the column mappings, tell it to update Table B, and call loader.WriteToServer(dataTable).
I am getting the following error:
Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
at Oracle.DataAccess.Client.OracleBulkCopy.PerformBulkCopy()
I have confirmed that the error occurs on the confirmation_number column, because if I don't load that column, the dataload succeeds.
Any ideas why the BulkCopy would be trying to turn a varchar(2) into a Number?
EDIT:
I have confirmed the following relevant issues:
This is happening on more than just the confirmation number. This
appears to only be a problem on string columns - whether from a
string to a string or a string to an integer.
This doesn't happen on every varchar2 column - last name and first name have no trouble.
This happens both on columns that have no null values (confirmation
number) and on columns that may have null values (street type).
Investigating the contents of the datatable at the moment before the
loader begins shows no difference in column definition between those
that successfully go in and those that do not.
I'm beginning to wonder if there's a bug in the BulkCopy itself and if I need to do this load using another utility.
EDIT:
Below is the trimmed down code.
Table A
CREATE TABLE "APPS_UNPROCESSED"
( "LAST_NAME" VARCHAR2(30 BYTE),
"FIRST_NAME" VARCHAR2(30 BYTE),
"MIDDLE_NAME" VARCHAR2(30 BYTE),
"NAME_SUFFIX" VARCHAR2(30 BYTE),
"GENDER" VARCHAR2(1 BYTE),
"DATE_OF_BIRTH" VARCHAR2(10 BYTE),
"ID" NUMBER,
:
:
"CONFIRMATION_NUMBER" VARCHAR2(30 BYTE) NOT NULL ENABLE,
"IS_FBO" NUMBER(1,0),
:
:
CONSTRAINT "VR_APPS_UNPROCESSED_PK" PRIMARY KEY ("CONFIRMATION_NUMBER")
Table B
CREATE TABLE "APPS_PROCESSED"
( "LAST_NAME" VARCHAR2(30 BYTE),
"FIRST_NAME" VARCHAR2(30 BYTE),
"MIDDLE_NAME" VARCHAR2(30 BYTE),
"NAME_SUFFIX" VARCHAR2(30 BYTE),
"GENDER" NUMBER(1,0),
"DATE_OF_BIRTH" DATE,
:
:
"CONFIRMATION_NUMBER" VARCHAR2(30 BYTE),
"ID" NUMBER,
"IS_FBO" NUMBER(1,0),
:
:
"ID" NUMBER NOT NULL ENABLE,
:
:
CONSTRAINT "VR_APPLICATION_PK" PRIMARY KEY ("ID")
Procedure
procedure getUnprocessedApps(results OUT sys_refcursor)
as
BEGIN
open results for
select
a.last_name
,a.first_name
,a.middle_name
,a.name_suffix
,decode(a.gender, 'M', 1, 0) as gender_id
,a.gender as gender_code
,to_char(to_date(a.date_of_birth, 'MM-DD-YYYY'), 'DD-mon-YYYY') as date_of_birth
,cast(a.confirmation_number as varchar2(30)) as confirmation_number
,a.id
,0 as is_fbo
:
:
from vr_apps_unprocessed a
fetching the data
DataSet data = new DataSet();
OracleConnection conn = null;
OracleCommand cmd = null;
OracleDataAdapter data_adapter = new OracleDataAdapter();
//fetch the data and load
using (conn = new OracleConnection(connString))
{
using (cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = "APPS.getUnprocessedApps";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("results", OracleDbType.RefCursor, ParameterDirection.Output);
conn.Open();
data_adapter.SelectCommand = cmd;
data_adapter.Fill(data, "results");
}
}
return data.Tables["results"];
setup the column mapping
private static Dictionary<string, string> ColumnMappings()
{
Dictionary<string, string> mapping = new Dictionary<string, string>();
mapping.Add("last_name", "last_name");
mapping.Add("first_name", "first_name");
mapping.Add("middle_name", "middle_name");
mapping.Add("name_suffix", "name_suffix");
mapping.Add("gender_id", "gender");
mapping.Add("date_of_birth", "date_of_birth");
mapping.Add("is_fbo", "is_fbo");
mapping.Add("confirmation_number", "confirmation_number");
mapping.Add("id", "id");
:
:
return mapping;
}
Load files
private static void loadFiles(DataTable dt, string connString)
{
OracleConnection orclconn = null;
OracleBulkCopy loader = null;
//now insert the data into Oracle
using (orclconn = new OracleConnection(connString))
{
orclconn.Open();
using (loader = new OracleBulkCopy(orclconn))
{
loader.DestinationTableName = "APPS_Processed"
foreach (KeyValuePair<string, string> k in ColumnMappings())
{
loader.ColumnMappings.Add(k.Key, k.Value);
}
loader.WriteToServer(dt);
} //end using oracle bulk loader
} //end using oracle connection
}
EDIT:
I have been unable to get the bulkcopy to work, but I have gotten the traditional method of using arrays to work: http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html
It is definitely slower than a successful bulk load, but at least I can get the data in. I'd still love if anyone has any ideas on why the bulkcopy itself keeps failing, though.
|
I believe the problem is in your "date_of_birth" column. you are passing a string and not a date. since dates are numbers, it tries to cast them, but it is not in a format it expect, you changed the order of months and days.
| 1 |
"date_of_birth"
|
How can I fix messy hair in Animal Crossing?
|
I time-warped in Animal Crossing: New Leaf so I could get to the award ceremonies for the Bug-Off. I time-warped a year ahead, and now my hair's all messy. How can I put my hair back to normal?
|
First, you will need to have a Shampoodle's on Main Street. You can get Shampoodle's by spending 10,000 Bell at the Able Sisters after unlocking Kicks. You can do this after spending at least 8,000 Bells in the Able Sisters after you have played the game for at least 10 days. Then, when Shampoodle's is open for business, she will ask you a couple of questions on how you want your hair to look. The process will cost 3,000 Bell, but will be worth it after you see the kind of hair you got!
| 1 |
Shampoodle's on Main Street
|
Adding elements into associative array in javascript
|
I'm trying to add elements into an Associative Array, which is colors = []
I want it to have the ["id":selected_color] but my browser keeps crashing (an infinite loop somewhere?)
I'm not sure if I'm adding the elements into the array correctly.
What is happening is that I'm clicking on a span element, which has its ID value set to a hexcode value, and I'm trying to capture that value and associate it with the selected._color
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
var selected_color = "";
var colors = [];
$(document).ready(function() {
$(".color_cell").click(function(){
// ADD MY COLOR TO SELECTED COLOR'S ASSOCIATIVE ARRAY
colors[$(this).attr("id")] = selected_color;
console.log($(this).attr("id"));
$(this).css({'background-color':'white'});
$(this).unbind('click');
updateDisplay(colors);
alert("hi");
});
$(".btnColor").click(function(){
// MAKE SELECTED COLOR BE ME
alert("hey");
selected_color = $(this).attr("id");
}); // end button handler
}); // end ready()
function updateDisplay(colors) {
jQuery.each(colors, function(key, value) {
//it seems to crash here...
$("#storage_display").html("var "+$("#storage_display").html()+" " +value);
});
};
</script>
|
Why don't you try just some normal javascript instead of
colors[$(this).attr("id")] = selected_color;
try using
colors.push(selected_color);
and instead of your jquery loop, try using
for(var i = 0; i < colors.length; i++) {
$('#storage_display').html('whatever your trying to do here use colors[i]');
}
I dont understand what you're trying to do in the loop but assuming it did work, the html will be something like 'var var var var var var hexcode hexcode hexcode hexcode hexcode'
| 0.888889 |
Why don't you try javascript instead of colors?
|
Can I delete my fork of a BitBucket repository, after the owner has accepted and merged my pull request?
|
I created a fork of a public repository on BitBucket, with the sole purpose of committing a pull request that fixed some bug. The pull request was accepted and merged. Now, I want to delete the repository, that has outlived its purpose. If I do that, will the changes be lost?
There is already a question about this same issue, but for GitHub. Apparently, on GitHub you can delete the repository before the request has been even merged, as it gets automatically saved in the target repository. I guess that on BitBucket, things will be similar, but I wanted to be sure.
|
I'm not sure if you could do it before it's merged, but you certainly should be able to afterwards.
| 0.888889 |
If you could do it before it's merged, you should be able to do it afterwards.
|
How to stop shell script if curl failed
|
I have script that used curl
when i pass wrong parameters to script curl failed but script continue executing.
I have tried use curl -f/--fail parameter but problem does not solved.
What is the best way to stop script?
I have founded my mistake.
I used curl command into another command
echo `curl --fail ... || exit 1`
After removing echo command curl become working properly.
Thank you for answer, it is also useful.
|
Just exit if curl ends with a non-zero exit code:
curl http://www.example.com || exit 1
Or, make your script exit on error:
set -e
curl http://www.example.com
| 0.888889 |
Set -e curl http://www.example.com
|
Should I avoid credit card use to improve our debt-to-income ratio?
|
We put all our expenses on a credit card and pay it off every month in order to get maximize our cash back. We never charge more than we have in the checking account, so we always pay it off. Should we reconsider doing this in order to improve our debt-to-income ratio?
Our goal is to be in the best position possible to get a mortgage in the next 3-12 months.
|
For scoring purposes, having a DTI between 1-19% is ideal.
From Credit Karma:
That being said, depending on the loan type you looking at receiving (FHA, VA, Conventional, etc), there are certain max DTIs that you want to stay away from. As a rule, for VA, you want to try to stay away from 41% DTI. Exceptions are made for people with sufficient funds in the bank (3-9 months) to go to higher DTIs. If you keep a 19% utilization overall, that will get you a higher score but it will also show that you have a monthly payment on a particular revolving credit account. While the difference between 729 and 745 seems like a lot of points, there are rules as to how the interest rates are determined. So you will find that many banks have the same or similar rates due to recent legislation in Dodd-Frank. In the days of subprime mortgages, this was not the case. Adjustable rate mortgages did not necessarily go away, the servicer just has to make sure that the buyer can weather the full amount once it reaches maturity, not the lower amount. That is what got a lot of people in trouble.
From "how interest rates are set":
Before quoting you an interest rate, the loan officer will add on how
much he and his branch want to earn. The branch or company sets a
policy on how little that can be (the minimum amount the loan officer
adds on to his cost) but does not want to overcharge borrowers either
(so they set a maximum the loan officer can charge) Between that
minimum and maximum, the loan officer has a great deal of flexibility.
For example, say the loan officer decides he and his branch are going
to earn one point. When you call and ask for a rate quote, he will add
one point to the cost of the loan and quote you that rate. According
to the rate sheet above, seven percent will cost you zero points. Six
and three-quarters percent will cost you one point.
In our example, at 7.125% the loan officer and branch would earn one
point and have some money left over. This could be used to pay some of
the fees (processing, documents, etc), which is how you get a "no fees
-no points" mortgage. You just pay a higher interest rate.
Where this scoring helps you is in credit card interest rates and auto loan and personal loan rates, which have different rate structures.
My personal opinion is to avoid the use of the credit cards. Playing games to try to maximize your score in this situation won't help you when you are talking about 20 points potentially. If you were at the bottom level and were trying to meet a minimum score to qualify, then I would recommend you try to game this scoring system. Take the extra money you would put on a credit card and save it for housing expenses. Taking the Dave Ramsey approach, you should have at least $1000 in emergency funds as most problems you encounter will be less than $1000. That advice rings true.
| 1 |
How to get a DTI between 1-19% is ideal for a credit score .
|
How do animal perceive distances with their eyes and ears
|
I am studying how animals (including the human beings) can perceive distances thanks to their eyes and their ears. I am focusing on the fact that they always go in pairs: two eyes, two ears, etc.
About the sight, I think our eyes use the parallax. But is this enough? Is this the only way we can perceive distances with them?
About the sounds, I think it is merely by interferometry, but I am not convinced, because the distances between our ears and the wavelength are not always comparable to one another.
What do you think about it?
Thanks in advance,
Isaac
|
Adding to Lawrence's answer, apart from the monocular cues like depth from shading, lighting, haze, geometrical structure and familiarity of objects, you also have binocular cues from the eye motor convergence system (eyes point at the spot you are looking at in 3d space) as well as the feedback from the lens focusing system.
All of these systems work together when you look at objects in the real world, but in for example 3d movies and tvs only some are active, which can cause various sorts of dizziness or headache among viewers.
Interestingly viewing plain old 2d photos of 3d objects/worlds does not infer this sickness at all..
With regards to hearing, apart from loudness and phase the auditory system also uses timing of onset, this obviously relates to phase discrimination depending on the audio frequency and size of the head. Furthermore, the spectral filtering of the signals at both ears is shaped by the asymmetrical shape of the outer ears, this allows the auditory system to gauge sound localization in front of, behind, above and below. Monaural cues include, as with vision, familiarity of certain sounds or speakers and how these sounds degrade by passing through air.
Several hundred million years of evolution has been pretty good at extracting every bit of useful information from all our senses :)
| 1 |
Monaural cues include depth from shading, lighting, haze, geometrical structure and familiarity of objects
|
Should I replace the Timing belt in 2004 Kia
|
I own a 2004 Kia Spectra. It only has 47,000 miles on it (I don't drive much) When I had the transmission fluid changed they said the 3 outer belts needed to be replaced due to dry rot. I am in Texas so guess this is possible. When I called to make the appt to take it in, the guy said I needed 'for maintenance' to have the timing belt replaced, as well as coolent, spark plugs and the three belts. Thus far I've not had any problems with my car and do regular oil changes, etc. What is your opinion please? I have friends that are saying there is No need. I'm an elderly female and don't want to be taken advantage of.
Thank you in advance.
|
Even if the timing belt is "probably" okay, you have to weight the costs and benefits of not replacing it. From what I can tell, this car has an interference engine, meaning if the timing belt breaks, the cylinders will smash into the valves. As long as they don't break off and also tear up the cylinders/combustion chamber, this is a difficult but doable job for someone with car repair experience to do themselves, but if you need to take it to a professional to repair, you're looking at a repair bill possibly exceeding the value of the car.
As such, if there's any good indication the timing belt needs replacement, I'd just do it. If the shop is asking too much, shop around for a cheaper price or get a book and do it yourself (admittedly it sounds like this option is not for the OP) -- but remember, if you mess up the timing when installing the new one, then in a best-case you're just going to get horrible engine performance and smoking, and in a worst case you'll smash the valves just like if the timing belt broke.
| 1 |
if the timing belt breaks, the cylinders will smash into the valves
|
keybinding in xterm to shift one line up using shift+up
|
follow urxvt: scroll just one line
How can we set keybindings so that shift+up can scroll one line up in xterm?
|
Use the X resources documented in the XTerm man page, particularly the "ACTIONS" section about 80% of the way down.
Create a file ~/.Xresources and put in it:
XTerm.VT100.translations: #override \
Shift <Key>Up: scroll-back(1) \n\
Shift <Key>Down: scroll-forw(1)
"Translations" is the base Xt library's name for key and mouse bindings. This sets bindings for the VT100 (terminal emulation) component of XTerm, overriding any existing bindings and setting Shift-Up to scroll up (or "back") one line, and Shift-Down to scroll down ("forw"ard) one line. We're making one long line so we're using backslashes at the end to mark continuation.
As with any use of .Xresources, you will need either to have the XENVIRONMENT variable set pointing to the right place, or use xrdb -merge ~/.Xresources to load the file into the resource manager explicitly.
| 0.777778 |
Use X resources documented in the XTerm man page
|
Java method called twice from C++ JNI NDK function
|
I have some C++ NDK code calling a Java method via JNI. The problem I have is that my Java method is getting called twice. It seems once I get a handle to the method using GetMethodID and then call env->NewObject w/ that method ID, my java function is called.
It is again, obviously called when I call env->CallVoidMethod(obj, mid) which is expected. I just am not sure why it is called when I create a NewObject?
C++ Code:
---------
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
jvm = vm;
start();
return JNI_VERSION_1_6;
}
void start() {
JNIEnv *env = NULL;
jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
jclass cls = env->FindClass("com/test/Test");
jmethodID mid = env->GetMethodID(cls, "StartApp", "()V");
jobject obj = env->NewObject(cls, mid);
if (mid != 0){
env->CallVoidMethod(obj, mid);
}
}
Java Code:
----------
public void StartApp(){
android.util.Log.e("Test", "Java Method Called from Native");
}
|
NewObject take the constructor as parameter, so
jobject obj = env->NewObject(cls, mid);
This will invoke the first StartApp(), but note that since it's not a proper constructor, this will cause you trouble.
For the constructor, according to the manual, This ID must be obtained by calling GetMethodID() with < init > as the method name and void (V) as the return type.
| 0.888889 |
NewObject take constructor as parameter
|
Subdomain or New domain for new company division - SEO
|
Someone has asked me about developing a site for a new division that this company is expanding to include in their services. They have purchased a domain for this new service, but I was wondering:
Since they already have an established domain with a Pagerank (3), would they be better suited with a subdomain (specialty.domain.com), redirected to from their new domain? Any SEO benefit here?
|
There are issues with redirecting a domain to a sub-domain that are often forgotten. One is the sub-domain will, at some point, have to stand on it's own. Often, if a domain is redirected to another, the question comes up regarding deleting the original domain. Any links, trust score, site score is passed using a 301 redirect, however, if the desire comes about to delete the original domain, then these things are lost. Using a redirect is not a bad solution, it often ends up being a temporary solution and the new domain or sub-domain must stand on it's own. It becomes imperative that the new domain or sub-domain gain links, a trust score, and site score on it's own.
If the existing domain is performing well, it should be a consideration if it still makes sense to keep the domain. A decision should be made in advance. It is fine to redirect to a sub-domain, you will suffer a small loss with any 301 redirect, but it may be wise to continue to with the original domain name if it makes sense. That is a business decision regarding branding and company identity. If the company decides that a sub-domain is best, then prepare yourself to work on the sub-domains standing for the inevitable day where the company will want to delete the original domain.
| 0.777778 |
301 redirects to a sub-domain are often forgotten .
|
What is the best place to start Warhammer 40k?
|
I've got three omnibus books containing 9 total Warhammer 40,000 stories. Before I mention which ones I've got, which book would you recommend as a good place to start the series?
|
In reply to Gilles and Horus
My personal recommendation is starting with a imperial guard series like gaunts ghosts or the lay chancers. They will give you a perspective of the average human. After that a space marine or a inquisition based series would be wise. The blood angels series is one i recommend due to its strong imagery and good story. After that it is up to you. The list i have is a expanded version of horus's answer minus the few i have not read.
Eisenhorn / Ravenor: Covers the Inquisition and the different Ordos. My personal favorite was the Ravenor series.
Ciaphas Cain: Hero of the Imperium / Ciaphas Cain: Defender of the Imperium by Sandy Mitchell: My one of my favorite series. The plot revolves around a hero of the Empire who believes himself to be a coward. Very light hearted compared to other series.
Ultramarines: A standard space marine series with themes of honor and duty. A great world but the characters are a little dry. The enemies are chaos and tyranids.
Grey Knights: I also enjoyed this series. Covering the grey knights and their wars against deamons. It covers the inquisition and its methods and it s relation to the grey knights.
Gaunt's Ghosts: an imperial guard series, among my friends it is either hated or loved. This series is considered the bread and butter of the imperial guard stories. The overall feel is that of band of brothers or another world war 2 series.
Blood Angels: A great story about a pair of brothers in the blood angel legion. I read the omnibus and i would recommend you do that also, there is a short story that reveals a another dimension the antagonist.
Last Chancers: This novel is an imperial guard novel that is about a penal legion and the main character Cage. Covering chaos, the tau, and 'nids. Truly a good series.
| 1 |
Imperial guard series like gaunts ghosts or the lay chancers .
|
Plot has red 'film', no error message
|
I am encountering really strange behavior: I wrote a function that plots values some data. After executing the code the resulting plot has the red 'error' colour, but only momentarily (maybe 0.1 sec). There is no error message, so the plot seems fine. However, when I export the graphic, the red colour is exported too. There seems no way to get the graphic without the red.
I am (in this case) not interested in what caused the error message but want to export the graphic without te red colour. Does anyone know how to do this?
I tried using Quiet[] but that did not help.
My code:
PlotBetaCI[whole_,everyminute_]:=
Module[
{len,linearmodels,betas,lows,highs},
len=Length[everyminute];
linearmodels=Quiet@LinearModelFit[Transpose[{#,whole}],x,x]&/@everyminute;
betas=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,1]]&/@linearmodels}];
lows=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,3,1]]&/@linearmodels}];
highs=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,3,2]]&/@linearmodels}];
ListPlot[{betas,Sequence@@Transpose[{lows,highs}]},Joined->{False,Sequence@@ConstantArray[True,len]},PlotStyle->Black,PlotMarkers->{Graphics[{Line[{{-1,-1},{1,1}}],Line[{{-1,1},{1,-1}}]},ImageSize->10],Sequence@@ConstantArray[Graphics[{Line[{{0,0},{0.04,0}}]},ImageSize->10],len]},ImageSize->Large,PlotRange->{Automatic,{Automatic,1.5}}]
]
The command to actually plot is (this produces the plot I am talking about)
PlotBetaCI[rmssd, everyminutermssd]
rmssd is a list of values. everyminutermssd has the same length, but depth 10.
|
The pink box shows a formatting error. You can disable highlighting of formatting errors for a specific object using Style:
Style[
Graphics[{Disk[], garbage}],
AutoStyleOptions -> {"HighlightFormattingErrors" -> False}]
You can also change the setting globally using the Preferences dialog (Edit - Preferences - Messages - Formatting error indications), or just for the current session using:
SetOptions[$FrontEndSession, AutoStyleOptions -> {"HighlightFormattingErrors" -> False}]
| 0.888889 |
Formatting errors for a specific object
|
Slowdown in large perl array
|
I'm currently running a perl program where I have to take a 1 million line text file, break it down into chunks (anywhere between 50 and 50,000 lines per chunk), and run some calculations and such on them. Right now, I load all of the data into array1. I take array2 and use it to pull just the chunks of data I need. I then do what I need to perform on array 2, and then go back and grab the next set.
example data
A, blah1, blah2
A, blah6, blah7
A, blah4, blah5
B, blah2, blah2
So I would grab the first three into array 2, sort them, then move on to the next set. My program works pretty well and efficiently to begin with, but it experiences a severe slowdown later on.
50K takes 50 seconds, 100k takes 184 seconds, 150k takes 360 seconds, 200k takes 581 seconds, and it only gets exponentially worse as the program continues (4500 seconds at line 500k)
No, I cannot use a database for this project, any suggestions?
my @Rows1=<FILE>;
my $temp = @Rows1;
for($k = 0; $k < $temp; $k++)
{
my @temp2array = ();
my $temp2count = 0;
my $thisrow = $Rows1[$k];
my @thisarray = split(',', $thisrow);
my $currcode = $thisarray[0];
my $flag123 = 0;
$temp2array[$temp2count] = $thisrow;
$temp2count++;
while ($flag123 == 0)
{
$nextrow = $tuRows1[$k + 1];
@nextarray = split(',', $nextrow);
if ($currcode eq $nextarray[0])
{
$temp2array[$temp2count] = $nextrow;
$k++;
$temp2count++;
}
else
{
$flag123 = 1;
}
}
}
I have edited my code to more resemble the answer below, and I've got these times:
50k = 42, 100k = 133, 150k = 280, 200k = 467, 250k = 699, 300k = 978, 350k = 1313
Its not exactly keeping linear, and by this trend, this prog will still take 14000+ seconds. I'll investigate other parts of the code
|
Does just running the code you show have the slowdown? If not, the problem is in the code that actually processes each @temp2array chunk, perhaps some variable(s) still having data left over from previous chunks.
| 0.777778 |
Does just running the code you show have the slowdown?
|
Which Windows 7 to install?
|
I have 2GB of RAM on my laptop, which is the max.
Should I install 32 bit version or 64 bit version?
|
The biggest issue you should care about is drivers.
Do 64bit drivers exist for your laptop? Check that before you do anything, as lot of hardware companies don't have any available. If you can't find Windows 7 drivers, usually the Vista drivers will work.
Ontop of that, if you are using your laptop for heavy-lifting applications that require a lot of memory, then 64bit is better. Though with 2gb of RAM it's barely going to make any difference for you, as 64bit excels because it can support more than the ~3gb limit of 32 bit windows. So the advantage is once you have more than 4gb of ram.
The heavy-lifting applications usually are 3D software: Maya, 3DS Max, or graphics applications such as Photoshop and Gimp. Also gaming on 64bit gives slightly faster framerates, though that's a product of the processor and motherboard not the operating system. Your existing games may not work on 64 bit Windows.
You are also likely to find some installers refuse to install on a 64bit version too, mostly from dumb installers looking at registry keys.
My choice would be stick with 32 bit Windows 7, as a laptop (atleast one that only has 2gb of RAM) is probably not going to be used for any of those applications, or gaming.
If you want another opinion Tomshardware has a few threads on it.
| 1 |
Do 64bit drivers exist for your laptop?
|
WACOM Bamboo FUN Pen&Touch
|
I’m using a 12.10 with Gnome desktop for now and just started to learn couple of things about it. I have a Lenovo i5 with a nVidia GeForce GT635M but because of numerous issues I use the default Nouveau driver for it.
I'm planning on buying a new graphic tablet, I haven’t used one yet. I’m considering a WACOM Bamboo FUN Pen&Touch Small . I’m not a professional and I won’t need something very expensive in the first place and this seems like a good choice. My only experience with drawing until now was been pen and paper.
Did a short search on the forum and found couple of tips and advises about installing this thing. I guess I’ll try those when I’ll have the tablet in my hands.
I just have a couple of questions before buying it:
For people who are using it with Ubuntu, would you recommend something else in this price range?. From my little google research there are pretty good reviews for this model but I’m open to suggestions.
Does anyone have a complete set of instructions for installing it(meaning something that will help me use all its features?
What app do you use for it, I have two or three apps that came with gnome but if there is something better you recommend I would like to hear about it?
I’m not a native English speaker so if there is something unclear or misspelled in my message I apologize.
|
I have already tried 2 wacom models and just yesterday a student who I am teaching Ubuntu to brought a Wacom tablet, the Bamboo Create one. For 12.10 and 13.04 (The ones I tested yesterday for the class) you can simply connect the device and it will work out of the box.
If you need to configure anything for it (Like sensibility, orientation...) you will need to go to the System Settings panel and select Wacom Tablet.
It should give you all options available for that particular tablet.
For programs that work with it, well we tested yesterday Gimp, Inkscape and even the Compiz Fire effect. It could also be used as a touchscreen to select items in the Desktop.
| 1 |
Wacom tablet for Ubuntu
|
Evaluating an integrals by appropriate substitution
|
i can't understand how to solve this issue: using an appropriate substitution, evaluate this integral:
$$
\int \frac{1+x²}{\sqrt{1+x}}\mathrm{d}x
$$
can any one solve this so i can understand how to do this.
|
When you are facing a radical which has a linear sum in it, it works well to use that as the basis of the substitution. Here, you would take $ \ u = x + 1 \ $ , which will give you $ \ du = dx \ $ . To deal with the numerator, you need to solve your substitution equation for $ \ x \ $ , giving $ \ x = u - 1 \ $ . The integral becomes
$$ \int \ \frac{1+ x^2}{\sqrt{1 + x }} \ dx \ \rightarrow \ \int \frac{1 + (u - 1)^2}{\sqrt{u}} \ du \ . $$
You would then multiply out the polynomial in the numerator.
The point in doing this is that you now have a polynomial divided simply by the square root of the variable, which will leave you with a set of terms in the integrand which are all just fractional powers of $ \ u \ $ , something which is much easier to integrate.
| 0.888889 |
Calculate a linear sum in the numerator
|
Jquery - Customizing the colorbox plugin
|
I'm using the colorbox plugin for modal popups. It's working nicely, but there's a main thing about it that seems wrong.
I have a form that pops up, and on submitting (or clicking a link) in the form, this might open another "colorbox" modal. It works smoothly, but there's one thing that bothers me.
As it is, colorbox seems to wait until it receives the response (via ajax) and then shows a "loading.gif" and starts to change size.
To me it makes more sense to have the "loading.gif" show as soon as they are opening a new colorbox modal. (and not just the image, I just mean that whatever happens when you open a new colorbox) It doesn't have to resize (obviously) but it's just annoying because some of my colorbox modals use webservices that are slow, so you might submit a form and nothing happens for literally 1 or 2 seconds. It'd be nice if it just would look like it was loading the next one for that time.
Ideas on how to do this?
|
It looks like the loading graphic is being shown onLoad, and the script tries to figure out the content type before this point. So if you have a slow web service, it may take time to realize the content type, thus not showing the loading.gif.
I did a quick test, and displaying the gif onOpen seems to work:
$(".myClass").colorbox({
onOpen:function(){
// taken from colorbox.css
$('#cboxLoadingGraphic').show();
},
onComplete:function(){
$('#cboxLoadingGraphic').hide();
}
});
| 0.888889 |
loading graphic is being shown onLoad
|
The $ABCD$ paralelograms sides are $AB,BC,CD,DA$. On these line segments there are points in the same order: $X,Y,Z,V$.
|
The $ABCD$ paralelograms sides are $AB,BC,CD,DA$. On these line segments there are points in the same order: $X,Y,Z,V$. We know, that: $$\frac{AX}{XB}=\frac{BY}{YC}=\frac{CZ}{ZD}=\frac{DV}{VA}=k$$
$k$ is a positive constant what is less then $\frac{1}{2}$. What is the value of $k$, if the area of $XYZV$ is 86% of the area of $ABCD$?
Can you tell me a step by step answer to this question?
|
Due triangle similarity (by drawing parallel lines) at a given fraction of sides it is square root of the ratio. If at mid point of each side quarter area is filled for central position example $ \sqrt{(1/4)} = 1/2$. In this case the fraction is:
$ \sqrt{.86} =~ .927362.$
or =~ $ (1- 0.927362) $ if you mean the other half side for the ratio.
| 0.666667 |
Due triangle similarity at a fraction of sides
|
stackoverflow.com/questions is not updating
|
Possible Duplicate:
Stack Overflow is not getting refreshed automatically
Every time I open stackoverflow.com and click on the "questions" tab, the page doesn't update with new questions. Why?
|
The main Stack Overflow pages do not use live-updating; it would be too much of a performance penalty on the server due to the high volume of questions.
| 0.888889 |
The main Stack Overflow pages do not use live-updating
|
Daydream with transparent background
|
I'm trying to implement a daydream service with a transparent background.
I wrote the following code:
public void onAttachedToWindow() {
super.onAttachedToWindow();
setContentView(R.layout.mydream);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
.
.
.
}
But when I start up the daydream, the background is only transparent for 1 second. After that it turns to black background.
Can anyone help me with this?
|
This question may have the answer you need:
How to create Transparent Activity in Android?
You can do that by creating a Transparent theme and applying it to your activity.
| 0.777778 |
How to create Transparent Activity in Android
|
Kernel density estimation across multiple UTM zones
|
I'm trying to compare the spatial distribution between two groups of fishing locations (for each of several different years) in the Bering Sea (lat's ~53 to 65N, long's ~ -178 to -158W. My preliminary explorations have used kernel density estimation (with an unconstrained plug-in bandwidth matrix) and then examined different overlap indices of their home ranges (quantified via utilization distribution overlap index and Bhattacharyya's Affinity) to compare similarities/differences (all performed in R).
However, I'm concerned about the interpretation of these data when the data may span more than one UTM zone. Most of my data are in UTM zone 3 with some data points seeping into zone 4. In more extreme cases, my data may span from zone 1 to 4.
Am I being really ignorant in thinking that I can compare across zone boundaries?
Since I am interested only in relative differences between calculations with the same distortion, will it not matter?
Should I simply make sure that I have my UTM origin set at the southwesterly most point of the data and I'm fine from there?
I've been reading StackExchange and other sites all morning and have seen several discussions about measuring across UTM zones, but I haven't been able to logically extend such responses to a method such as this one.
Thank you for your time and expertise!
|
I suggest (as Vince) to put the center of your custom projection in the middle of the study area at 168 W 59 N.
The following projections might give best results:
+proj=laea +lat_0=59 +lon_0=-168 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
+proj=aea +lat_1=53 +lat_2=65 +lat_0=59 +lon_0=-168 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
+proj=tmerc +lat_0=59 +lon_0=-168 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
They look pretty much the same (with the UTM zones as reference):
| 0.888889 |
Custom projections at 168 W 59 N
|
How can pKas differ across similar protons of the same atom?
|
For example, citric acid has three acidic protons, all of which are carboxylic acids. Despite being part of the same functional groups, they all have very different pKas. Why (and how?) is this?
|
Let's begin this discussion with the simpler oxalic acid.
O
#
HO-C-C-OH
#
O
There are two carboxylic acid functional groups, and there are two different pKa's. This is because double deprotonation does not happen simulateneously. One gets deprotonated first, then the other. After the first deprotonation, the residual molecule has a negative charge. The result:
O
#
HO-C-C-O~
#
O
Is much less acidic because the presences of the carboxylate functional group changes the acidity.
Let's continue the discussion with the (still simpler) alpha-chlorosuccinic acid:
Cl H O
| | #
HO-C-C-C-C-OH
# | |
O H H
The acid closer to the chlorine is more acidic because the chlorine is strongly electron withdrawing, and 'pulls' the electrons out of the carboxylate function, which then 'pulls' electrons away from the hydrogen, making it more acidic. This effect decreases with distance, so the chlorine pulls on the acid function farther away less strongly.
In a more generalized way, remote groups will modify acidity because of electron withdrawing or donating effects, but the farther away from the acid function, the less effect there is.
For citric acid, there are actually two different flavors of acid function, so one of the kinds will be intrinsically more acidic before deprotonation because of the remove effect. However, because of the sequential deprotonation discussed above, all three will have different pKa's
| 0.888889 |
Double deprotonation does not happen simulateneously
|
Get raw output from web server
|
For research I am looking to get the actual raw output that apache sends when responding to a request, including all get data, headers, and the html. How would I go about this? I have tried:
wget --output-document=response.txt -S "http://thewebsiteinquestion.com"
This shows me the response headers all layered out nicely and sends the HTML to the response.txt, but I really want to see raw text and how this is formatted.
|
Add the --save-headers option to the wget command line.
| 1 |
Add the --save-headers option to the wget command line
|
Sinks and Sources
|
I need to find a differential equation $x'=f(x)$ that has three equilibrium points that are
all sinks;
all sources.
So two differential equations total. Help!
|
hint: pay attention root of this equation x'=f(x) is equilibrium points let $f(x_0)=0$ therefore$$if\quad f'(x_0)\lt0 \quad then\quad x_0 \quad is\quad sink $$ and $$if\quad f'(x_0)\gt0 \quad then\quad x_0 \quad is\quad source $$ now you can find $f(x)$ for "1" let $f(x)=(x-a)(x-b)(x)$ s.t $f'(x)=3x^2-2(a+b)+ab\lt0$ then calculate lower bound and upper bound for a,b also do it for second part $f(x)=(x-a)(x-b)(x)$ then find a,b such that $f'(x)=3x^2-2(a+b)+ab\gt0$
| 0.666667 |
Find $f(x)$ for "1"
|
GarageBand not starting after Snow Leopard upgrade
|
Starting four days ago, I wasn't able to open any of the icons at the bottom of the page of my MacBook. I downloaded Snow Leopard, and now I can open all but GarageBand. This is a complete mystery to me.
I'm currently at OS X 10.6.3. (my Mac was bought used, do I need something newer to run Garageband?. How can I get GarageBand to run again?
|
You need a GarageBand version 6.05 from here.
And you need to update your Snow Leopard to 10.6.8
| 1 |
GarageBand version 6.05 from here
|
Change Width of Object on Screen Resize
|
How do I use Javascript to change the width of an object when the screen is resized to a smaller width? When the screen is resized back to the bigger size, I want the bigger object.
|
The best way to handle an object size in a responsive screen is through a relative size on css, like vihan1086 said. This could be made like this:
<div style="width: 75%">My Content</div>
This would make this element fill 75% of the screen, no matter the size of the screen.
If you really want to do that in JS, you could do something like this with the help of jQuery
$(window).resize(function() {
var window_width = $(window).width();
if(window_width < 300) {
$("#myDiv").width(100);
}
});
| 0.888889 |
How to handle an object size in a responsive screen?
|
How do you prove $S=-\sum p\ln p$?
|
How does one prove the formula for entropy $S=-\sum p\ln p$?
Obviously systems on the microscopic level are fully determined by the microscopic equations of motion. So if you want to introduce a law on top of that, you have to prove consistency, i.e. entropy cannot be a postulate.
I can imagine that it is derived from probability theory for general system. Do you know such a line?
Once you have such a reasoning, what are the assumptions to it?
Can these assumptions be invalid for special systems? Would these system not obey thermodynamics, statistical mechanics and not have any sort of temperature no matter how general?
If therodynamics/statmech are completely general, how would you apply them the system where one point particle orbits another?
|
The functional form of the entropy $S = - \sum p \ln p$ can be understood if one requires that entropy is extensive, and depends on the microscopic state probabilities $p$.
Consider a system $S_{AB}$ composed of two independent subsystems A and B. Then $S_{AB} = S_A +S_B$ and $p_{AB} = p_A p_B$ since A and B are decoupled.
$$
S_{AB} = - \sum p_{AB} \ln p_{AB} = -\sum p_{A} \sum p_B \ln p_A -\sum p_{A} \sum p_B \ln p_B
$$
$$
= -\sum p_{A} \ln p_A - \sum p_B \ln p_B = S_A + S_B
$$
This argument is valid up to a factor, which turns out to be the Boltzmann constant $k_B$ in statistical mechanics: $S = - k_B \sum p \ln p$ which is due to Gibbs, long before Shannon.
| 0.888889 |
The functional form of the entropy
|
Why does my switch need to be wired in this fashion?
|
Today was my first foray into electronics since high school, in the form of some simple Raspberry Pi experiments. I managed to get a circuit working where a switch controlled an LED with a potentiometer to control the brightness of the LED.
However, I am confused by the wiring of the switch. Firstly, here's a photo of my amazing work:
NOTE: the black lead on the potentiometer is not connected to anything (hard to tell in the photo). Also, I realised afterwards that I could have just inserted the potentiometer into the breadboard rather than soldering wires to it. Noob mistake (one of many).
Here's an attempt at a schematic (also probably wrong because I don't know what I'm doing):
simulate this circuit – Schematic created using CircuitLab
As you can see, I used a PiFace, which comes with the four switches located at the left and towards the bottom of the photo. It is the wiring of this switch that befuddles me. Since each switch has two terminals, I was expecting one terminal to act as an input and the other as an output. That is, I just feed my circuit through those two terminals and job done. But that didn't work.
I managed to find this image online:
This is what prompted me to guess the configuration below, which works. However, I don't understand why it works. Nor do I understand why there are two terminals for each switch if only one seems to be used. I suspect the clue is embedded within the text in the above image:
The four switches, numbered S1 to S4 are connected in parallel to the
first four (0-3) inputs
However, I do not understand what this means. Perhaps a practical example of how I would use each terminal and an explanation of why the grounding is necessary would help my understanding.
|
Read the data sheet before you start connecting to something. Your assumption that because there are nine terminals and four switches that 'each switch has two terminals' is unfounded.
The 9 terminals are 8 input channels and ground. As the text you quoted says, the switches are connected between the first four channels and ground, so the connection in your photo agrees with the schematic.
| 1 |
'each switch has two terminals'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.