sqlalchemy-migration generates wrong script for db.func.current_timestamp()

Question: I use a postgresql9.4+flask+sqlalchemy in my current project. For making database migrations I decided to use sqlalchemy-migrate. But I've met the problem that this tool does not represent default value for the field correctly. To simplify my question I isolated the problem. My project looks like this:
flask_sqlalchemy_migration
├── app
│   └── __init__.py
├── config.py
├── db_create.py
└── db_migrate.py

./app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

class Base(db.Model):
    # __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())

./config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))

# database settings
DBMS = 'postgresql'
adapter = 'psycopg2'
user = 'flask_sqlalchemy_migration_db_user'
host = 'localhost'
port = '5432'
database = 'flask_sqlalchemy_migration_db'

SQLALCHEMY_DATABASE_URI = DBMS + '+' + adapter + '://' + user + '@' + host + ':' + port + '/' + database
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
SQLALCHEMY_TRACK_MODIFICATIONS = True

./db_create.py
#!env/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path

db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))

./db_migrate.py
#!env/bin/python
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%03d_migration.py' % (v+1))
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec(old_model, tmp_module.__dict__)
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI,
                                          SQLALCHEMY_MIGRATE_REPO,
                                          tmp_module.meta,
                                          db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v))

Up to this point everything's fine. I can run db_create.py and db_migrate.py, and it'll create initial database with base table and appropriate columns. The problem begin when I add "modified_at" field to the Base model:
class Base(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime,      default=db.func.current_timestamp())
    + modified_at = db.Column(db.DateTime, default=db.func.current_timestamp(),
                        onupdate=db.func.current_timestamp())

Then, if I run ./db_migrate.py I'll get such error:
File "/Users/ruslans/workspace/python/flask_sqlalchemy_migration/db_repository/versions/002_migration.py", line 10
    Column('created_at', DateTime, default=ColumnDefault(<sqlalchemy.sql.functions.current_timestamp at 0x108e7b1d0; current_timestamp>)),
                                                         ^
SyntaxError: invalid syntax

Indeed, if I go to the ./db_repository/versions/002_migration.py I'll find there incorrect code:
from sqlalchemy import *
from migrate import *

from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
base = Table('base', post_meta,
    Column('id', Integer, primary_key=True, nullable=False),
    Column('created_at', DateTime, default=ColumnDefault(<sqlalchemy.sql.functions.current_timestamp at 0x108e7b1d0; current_timestamp>)),
    Column('modified_at', DateTime, onupdate=ColumnDefault(<sqlalchemy.sql.functions.current_timestamp at 0x108e7b518; current_timestamp>), default=ColumnDefault(<sqlalchemy.sql.functions.current_timestamp at 0x108e7b400; current_timestamp>)),
)

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['base'].columns['modified_at'].create()

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['base'].columns['modified_at'].drop()

Please, if anyone knows why it happens and what I can do with it - let me know. I use

Flask==0.11.1
Flask-SQLAlchemy==2.1
psycopg2==2.6.2
SQLAlchemy==1.1.2
sqlalchemy-migrate==0.10.0
Answer: Just modify you version script (e.g. ./db_repository/versions/002_migration.py) manually and replace representations with usual python code.
So, replace sqlalchemy.sql.functions.current_timestamp with:
from app import db
...
Column('modified_at', DateTime, onupdate=ColumnDefault(db.func.current_timestamp) ...


Strategy for number of non-negative integers solutions such that $x_1+x_2+\frac{\enspace\enspace\enspace}{}+x_5 = 50$

Question: I'm trying to figure out the number of solutions to the following problems, although I'm not entirely sure what strategy I should use to solve these.

Combinations of non-negative integers $x_1+x_2+\frac{\enspace\enspace\enspace}{}+x_5 = 50$ given:
$(*) \enspace 0 \leq x_1, \frac{\enspace\enspace\enspace}{}, x_4 \enspace\wedge \enspace x_5 \leq 5$
$(**) \enspace 0 \leq x_1, \frac{\enspace\enspace\enspace}{}, x_5 \enspace\wedge\enspace x_1-x_2-x_3+x_4+x_5 = 30$
$(*\!*\!*) \enspace 0 < x_1, \frac{\enspace\enspace\enspace}{}, x_3,\enspace\wedge\enspace 0 \leq (x_4, x_5) \leq 5$

For $(*)$ I know I can fix $x_5$ from $0-5$, and solve $x_1+x_2+x_3+x_4= 50-x_5$, then add these solutions together. But I'm not sure what strategy I could use for $(**)$ and $(*\!*\!*)$. Could anyone give me some direction?
Also note the $<$ instead of $\leq$ at $(*\!*\!*)$.
Thanks in advance.
Answer: For the second case, adding the equation in the problem statement to the one in the case gives:
$$x_1 + x_4 + x_5 = 40,$$
and subtracting them gives
$$x_2 + x_3 = 10.$$
For the third case, it's much the same as the second case, except you set $x_4 + x_5$ to $0, 1, 2, ... 10$ and simultaneously set $x_1 + x_2 + x_3$ to $50, 49, 48, ... 40,$ with the further contstraint that $x_1, x_2, x_3$ are positive.
Comment: So I'd multiply the number of solutions to $x_1+x_4+x_5 = 40$ with the number of solutions to $x_2+x_3 = 10$ ?
Comment: If you're looking for combinations, then you may need to remove some duplicates after you multiply.
Comment: given that $x_i$ and $x_j$ are distinguishable, would that be necessary?


Item with session: , reportPath: , userName:  not found in the database

Question: In ReportManager I have many users complaining about this error. When I sift through the RS logs I see the following error many times for different users:
session!ReportServer_0-2!1e40!04/20/2011-09:13:56:: i INFO: LoadSnapshot: Item with session: zlq0epfrvvvfagbyyda2drbm, reportPath: , userName: PROD\user not found in the database
library!ReportServer_0-2!1e40!04/20/2011-09:13:56:: e ERROR: Throwing Microsoft.ReportingServices.Diagnostics.Utilities.ExecutionNotFoundException: Execution 'zlq0epfrvvvfagbyyda2drbm' cannot be found, ;
 Info: Microsoft.ReportingServices.Diagnostics.Utilities.ExecutionNotFoundException: Execution 'zlq0epfrvvvfagbyyda2drbm' cannot be found
ui!ReportManager_0-1!216c!04/20/2011-09:13:56:: Unhandled exception: Microsoft.Reporting.WebForms.ReportServerException: Execution 'zlq0epfrvvvfagbyyda2drbm' cannot be found (rsExecutionNotFound)
   at Microsoft.Reporting.WebForms.ServerReport.GetExecutionInfo()
   at Microsoft.Reporting.WebForms.ServerReport.SetExecutionId(String executionId, Boolean fullReportLoad)
   at Microsoft.Reporting.WebForms.ServerReport.LoadFromUrlQuery(NameValueCollection requestParameters, Boolean fullReportLoad)
   at Microsoft.Reporting.WebForms.ReportDataOperation..ctor()
   at Microsoft.Reporting.WebForms.HttpHandler.GetHandler(String operationType)
   at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Clicking on view report again, or hitting back on the browser and running the report again often seems to work - but I don't consider these viable solutions.
I've found dozens of postings on the web and have tried most of them without success. These included upping the SessionAccessTimeout & SessionTime values in the ReportServer.ConfigurationInfo database as well as setting reports to not timeout report execution and upping timeouts in the RS Web.config & rsreportserver.config.
This error will happen on reports that take seconds to run as well as longer running ones. We're running SSRS 2008 with RSWindowsBasic auth over SSL (this was recently changed from RSWindowsNTLM).
Any thoughts/input would be greatly appreciated.
Answer: Please try the following, this should fix the issue:

On the server, edit C:\Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config
Set EnableAuthPersistence in rsreportserver.config to False

Regards,
M.R.
Answer: Maybe your issue is here :
PROD\user not found in the database

Comment: I've double checked that the user (in this case PROD\user) is in the RS db - not only that, but I can also find the session in the RS db ... still it complains that it can't find it.
Comment: Did you try to recreate from scratch the reporting services database ?


Objective C: "_main", referenced from: Start in crt1.3.1.o error

Question: Trying to compile a iPhone/iPad application with SDK3.2 and am getting this error:
Undefined symbols:
"_main", referenced from:
Start in crt1.10.5.o
Symbol(s) not found
Collect2: Id returned 1 exit status

I think it's telling me that it's somehow trying to work with code from another SDK but searching the web has not provided any clear answers.
Anyone able to guide me on this and what to look for?
Comment: are you using eclipse or Xcode....?
Comment: I'm using XCode. I just noticed that I'm getting two different crt references as well. Definitely picking up another SDK somehow.
Answer: It looks like you haven't provided a main function in any of your source files. The crt object file is most likely the startup code which sets up your environment then calls main (CRT usually stands for C runtime, when it's not being used to mean Cathode Ray Tube, which it shouldn't any more, that being dead technology and all).
The Undefined symbols: "_main" ... simply means that the linker has discovered crt1.10.5.o needs the _main symbol satisfied and none of the files provided are satisfying it.
Short of seeing the actual linker command line, we can't be certain what's being included. You should check your source code and confirm or deny the existence of main()? And that it's inluded in the build?
Comment: Doh! I was thinking I had a main function being included when it wasn't. Thanks. So obvious :-)
Answer: There appears to be several possible causes.
I ran into this problem when the Perform Single-Object Prelink build option was checked
(GENERATE_MASTER_OBJECT_FILE = YES).
Comment: I was getting an error for _main undefined in Arm64 architecture in my release build. Setting the **Perform Single-Object Prelink** to "No" is what fixed it.
Answer: I got this when I opened a Swift project in Xcode 5.  When I opened it in Xcode 6, it worked fine.


Resize childcontrols in a panel automatically in asp.net

Question: i have a question about automatically resizing childcontrols of a panel if the panel change the width or the height. I use Asp.net (vb.net). Is there an extender or a property of the panel which allows this?
Or is there another panel which has the possiblity to auto resize their controls?
Or a javascript (jquery) plugin which allows resizing. I know the jquery.ui resiziable plugin, but i don't know if the plugin allows me to resize the childrencontrols when i change the size of the main panel with textboxes for example.
So i want to set the width for my button to 100px and add it to my panel like
<code>main_panel.controls.add(btn)
</code>
On my testpage i have two textboxes which allows me to resize the panel, the main panel with the button as his childrencontrol and another button for submiting the panelresizing.
i hope anyone understand me, my english is waste(:
Answer: There multiple solutions to your problem depending on your knowledge/requirements.

you can set a fixed size in when you add the controls to the panel
(with .NET)
you can set up flexible rules with css which automatically make the controls inside the div or even set them all the same fixed size the div will scale
you can do this with script as well, target all the elements and make them the same size

Depending on your need (eg does the user do the resizing? or is it window resizing?) I find it the easiest to set up solution 2 and then add an event listener when needed. For instance when the project requires re-sizing when the user sizes his browser window.
Just be careful though the window resize event is very "heavy" and gets triggered a lot so use it only when absolutely needed
English is not my native tongue as well so I hope I understood your question; if not just shoot :)
(try to avoid option 1, it is the least flexible and scalable)


Scale inline SVG with DIV wrapper

Question: Is it possible to scale an inline SVG without touching the SVG? So that only the wrapper div is able to change the width / height according to the image ratio?
Here is my code:
https://jsfiddle.net/sekmwfdg/1/

  <svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-gb" width="640" height="480">
    <defs>
      <clipPath id="a">
        <path fill-opacity=".67" d="M-85.333 0h682.67v512h-682.67z"/>
      </clipPath>
    </defs>
    <g clip-path="url(#a)" transform="translate(80) scale(.94)">
      <g stroke-width="1pt">
        <path fill="#006" d="M-256 0H768.02v512.01H-256z"/>
        <path fill="#fff" d="M-256 0v57.244l909.535 454.768H768.02V454.77L-141.515 0H-256zM768.02 0v57.243L-141.515 512.01H-256v-57.243L653.535 0H768.02z"/>
        <path fill="#fff" d="M170.675 0v512.01h170.67V0h-170.67zM-256 170.67v170.67H768.02V170.67H-256z"/>
        <path fill="#c00" d="M-256 204.804v102.402H768.02V204.804H-256zM204.81 0v512.01h102.4V0h-102.4zM-256 512.01L85.34 341.34h76.324l-341.34 170.67H-256zM-256 0L85.34 170.67H9.016L-256 38.164V0zm606.356 170.67L691.696 0h76.324L426.68 170.67h-76.324zM768.02 512.01L426.68 341.34h76.324L768.02 473.848v38.162z"/>
      </g>
    </g>
  </svg>

It should work for all modern Browsers + IE 11
Comment: Use **viewBox**: this  `` instead of this `` If no width and height declared the svg will take the size of yhe `wrapper `
Answer: You should add viewBox="0 0 640 480" to you svg tag and it will take width and height from its parent container

  <svg xmlns="http://www.w3.org/2000/svg" id="flag-icon-css-gb"  viewBox="0 0 640 480">
    <defs>
      <clipPath id="a">
        <path fill-opacity=".67" d="M-85.333 0h682.67v512h-682.67z"/>
      </clipPath>
    </defs>
    <g clip-path="url(#a)" transform="translate(80) scale(.94)">
      <g stroke-width="1pt">
        <path fill="#006" d="M-256 0H768.02v512.01H-256z"/>
        <path fill="#fff" d="M-256 0v57.244l909.535 454.768H768.02V454.77L-141.515 0H-256zM768.02 0v57.243L-141.515 512.01H-256v-57.243L653.535 0H768.02z"/>
        <path fill="#fff" d="M170.675 0v512.01h170.67V0h-170.67zM-256 170.67v170.67H768.02V170.67H-256z"/>
        <path fill="#c00" d="M-256 204.804v102.402H768.02V204.804H-256zM204.81 0v512.01h102.4V0h-102.4zM-256 512.01L85.34 341.34h76.324l-341.34 170.67H-256zM-256 0L85.34 170.67H9.016L-256 38.164V0zm606.356 170.67L691.696 0h76.324L426.68 170.67h-76.324zM768.02 512.01L426.68 341.34h76.324L768.02 473.848v38.162z"/>
      </g>
    </g>
  </svg>

Scale inline SVG with DIV wrapper


Can't get my Belkin N150 wireless adapter to work, stuck on "setting network address"

Question: I have installed Kubuntu 15.10 and everything is great, aside from the fact that I just cannot get my Belkin N150 Wireless USB adapter to connect to my wifi.
It shows my Network, but when I try to connect it gets stuck on "Setting network address", until it shows the notification "IP configuration is unavailable".
What makes this so strange is that I can get the adapter to work without any issues on other Linux distros like Mint or Manjaro, it's just Kubuntu that wont work with it.
I can also use different wireless adapters, I borrowed my brother's and it connected just fine.
I'm super confused by this all and really need some help!
Thanks a million,
Alex
Answer:
Open or search for the application Software Sources.
Click the rightmost tab: "proprietary drivers" or so.
Check all the boxes listed. (pass if none are)
When a window appears asking to update, click Ok or so.
When that finishes, click the leftmost tab and ensure that both universe and multiverse are checked (or whatever).
Close Software Sources, then open a terminal and run:
sudo apt-get update; sudo apt-get upgrade

Reboot.
Try to connect to WiFi.
If this does not work, search online for how to install proprietary drivers for your device.
Comment: Why da downvote tho?


pthread_join hangs indefinitely __lll_lock_wait_private()

Question: I have multithreaded application where I spawn a few threads and do a pthread_join upon completion.
The main thread spawns threads and waits on pthread_join() for the worker threads to join. I am facing a issue where the main thread is waiting indefinitely in pthread_join() and all the worker threads have exited, leading the program to hang.
I identified that all worker threads have exited by checking info thread on gdb since it lists only the main thread.
 Its is known that calling pthread_join() on a exited thread will return immediately. But this seems different. This is the gdb stack trace.
#0  0x00007f45fefebeec in __lll_lock_wait_private () from /lib64/libc.so.6
#1  0x00007f45fef68a6f in _L_lock_5333 () from /lib64/libc.so.6
#2  0x00007f45fef62408 in _int_free () from /lib64/libc.so.6
#3  0x00007f45ffbe5088 in _dl_deallocate_tls () from /lib64/ld-linux-x86-64.so.2
#4  0x00007f45ff9bde67 in __free_stacks () from /lib64/libpthread.so.0
#5  0x00007f45ff9bdf7f in __deallocate_stack () from /lib64/libpthread.so.0
#6  0x00007f45ff9bff93 in pthread_join () from /lib64/libpthread.so.0
#7  0x00007f45f87a6fe1 in waitForWorkerThreadsToExit () at src/server.c:133
#8  ServerLoop (arg=<optimized out>) at src/server.c:662
#9  0x00007f45ff9bee25 in start_thread () from /lib64/libpthread.so.0
#10 0x00007f45fefde34d in clone () from /lib64/libc.so.6

I am on CentOS7 and Linux kernel 3.10
Can someone help? TIA
Comment: `_dl_deallocate_tls` sounds like it has to do with thread-local storage; do any of your threads use that feature?  If so, you might try temporarily disabling it and see if that makes the fault go away.
Comment: @JeremyFriesner yes we use thread-local storage extensively. I am afraid that it cant be disabled.
Comment: You say, "the worker threads have exited." What does that mean? What caused them to "exit?" Your main thread appears to be waiting for a mutex. Is it possible that one of the "workers" was forcibly _killed_ while holding the lock?
Comment: To get help, you need to add a few things: 1. you should tell which exact version of GLIBC you are using. 2. you should install libc6-dbg or similar package (`debuginfo-install -y ...`) and get the "hang" stack trace with file/line info. With that, we'll be able to tell *which* lock `libc.so.6` is blocking on.
Comment: (GNU libc) 2.17 is the glibc version @EmployedRussian
Answer: One of the other threads is leaving without relinquishing the lock. As suggested here you can check the thread id for owner of this mutex to know which thread is the culprit.


What features to look for a gaming mouse that works as a full-time mouse?

Question: What should we look for in a gaming mouse that would also be used for other stuff?
Obviously any gaming mouse will work fine for anything else, but, for instance, I wish to have 2 axis wheel for horizontal scrolling (use it a lot on internet browsing and image manipulation and yes, I'm on a mac). So, which other feature a gaming mice usually lacks that we should look for?
Here are few more instances of features I could think of:

Are there particular advantages to laser, optical or infrared tracking options? I've read somewhere laser mice are bad options for irregular surfaces.
Does DPI matter? Is this a feature I should consider? If so, are there any relevant thresholds?
What ergonomic features matter? Handedness, shape?
Obviously the best choice is wired mouse, but just wondering about technical aspects: battery and responsiveness wise should I look for bluetooth or other wireless technology?
As for wheels, is there any kind of 2 axis wheel that will not be bad for gaming?
Comment: The way this is worded still makes it sound like you're looking for a specific product recommendation.  Price especially, isn't something that stays static enough to include in a feature set.
Comment: Looks like it got closed anyways.  If you're looking to fix it up, you may want to do something about the DPI option; it's very subjective.  Your last point, `why nobody came with...` isn't constructive.  Your other points are also excluding options, which still makes it look like you're asking for a product recommendation.  I'd recommend limiting it to the aspects that would make it a good overall mouse.
Comment: Whoever already voted this negatively, I think this is clearly a technical hardware question, allowed in the FAQ, and far from asking shopping advice. Would you mind explaining why downvoting?
Comment: Questions not allowed in the FAQ get close voted. Down votes have little to do with whether your question is *on topic* and everything to do with whether the voter thinks it's a *good question* that reflects research effort, is clear, and useful.
Comment: @LessPop_MoreFizz fair enough. Thanks for the feedback. I was hoping this was a question more people would have. Apparently not.
Comment: @fbueckert advice taken, removed those parts. hope it's better now. :-)
Comment: 2 axis wheel mice generally work just by emulating left/right arrow key presses. The only factor that matters there is that it's hard to accidentally horizontally scroll
Comment: @BenBrocka those are not 2 axis, those only have horizontal buttons added to the wheel. Only 2 mouses I know with 2 axis are Magic and Mighty, and both are terrible for gaming among many reasons because of the horizontal scrolling.
Comment: @fbueckert looks like you and Ben already did the great and very welcomed editing job. But I don't have any option to vote for re-opening! :-(
Comment: Oh, *those*. Yeah, those are most definitely not ideal for gaming
Answer: Tracking technology
Laser mice are generally the best, though their extreme precision occasionally causes problems with awkward surfaces. But I play on a rough wooden table with my laser mouse and I rarely notice when I'm moving over the wood instead of my mousepad. Optical doesn't work well with reflective or black surfaces. I'm not really sure what the complaint about laser is about honestly. I am currently unable to find a surface this cheapo laser mouse can't work perfectly on.
DPI
The best thing you can do is have a DPI switching mouse. This has two benefits; the first is letting you immediately switch the mouse movement speed (go from instant-turning speed to super precise sniping movements) and the second is letting you find exactly how sensitive you're comfortable with the mouse being for a given application or surface. Since I'm used to my high-DPI mouse I don't really switch it down (or all the way up) that often, but it's a nice feature to have.
If you want high DPI (I recommend it) again, laser is best; they're usually double optical or more. My Logitech G500 is ridiculously sensitive at 5700 max DPI, but right around 2000 feels nice. Remember if your mouse is too sensitive you can lower the pointer speed via software.
Ergonomics
For ergonomic factors, get a "handed" mouse if at all possible. If you're Left Handed you might go with an ambidextrous mouse (or if your partner is differently-handed and will use it as much as you do), but generally a "handed" mouse is far more comfortable to grip.
Size
Depending on your grip, get a mouse big/small enough for you. My hands are large so I have to scrunch up my hands (claw grip) or let my palm all off the mouse (fingertip grip). To palm-grip the mouse I need a mouse with a big "butt". Razer has a good guide to grip styles if you're confused by these terms or want more info on grip styles.
Weight
Weight-adjustable mice are also nice. High-DPI, low weight mice can be a pain to use; I prefer them a bit heavier, but the best thing you can do is manually adjust the weight. This sounds silly to some but adjustable weights are pretty common in mid to high end gaming mice.
Wireless
I've had issues with Bluetooth but what really matters is interference; the more wireless devices you have the more likely there's some interference going on. I've had issue with bluetooth and non-bluetooth devices.
Battery really shouldn't be a concern here; your mouse should last weeks between charges no matter what. General battery specs should be listed by the mouse anyway, so there's no need to consider which tech is going to eat more battery.
Multi-axis/multi-touch mice
For "two axis" wheels, if you mean Apple's multi-touch mince, those are terrible for gaming. Physical buttons are a must for one thing. If you mean horizontal scroll "tilt" wheels they usually don't get in the way of gaming, just make sure it's not too sensitive. My Logitec G500 requires a bit of force to press the horiz scroll which is good, an older Microsoft wireless mouse was sensitive enough I often accidentally pressed the horizontal scroll buttons while moving the wheel.
Comment: I guess that tells me: get 2 mouses.
Answer: Part 1: The lasers will be more accurate then the infra-red. Also they are extremely useful for anyone doing work with Art of Photos
Part 2: The higher the DPI that you have, the more precise the movements with the mouse, but also increased mouse sensitivity. Most manufactures have built in buttons on their mouses that allow you to change the DPI on the fly, this can be useful for gaming e.g. lowering the sensitivity and DPI while looking down the scope of a sniper rifle in Battlefield 3.
Part 3: Bluetooth and wireless mouses are not recommended for gamers, because signal may be lost or disrupted. Also the signal can be effected by objects between the mouse and receiver. As for battery life, it is recommended to keep an extra pair of batteries handy, unless that is the mouse comes with a docking station for charging when not in use or a wireless mouse that can also function as a wired mouse when plugged in or a wireless mouse that can also function as a wired mouse when plugged in.
Part 4: The 2 axis mouses are all personal choice. Myself as a gamer, I choose to stay away from 2 axis mouses, but it is your choice to use one or not.
Comment: quite evasive answer in general and little technical information added there... also, you mentioned lasers and infrared, but nothing about optical or why someone would say lasers are actually bad for gaming. at any pace, thanks for taking the time and trying to help! :-)
Comment: Never said lasers where bad for gaming, just that they are more accurate then infrared, and therefore will be more useful when doing work with art or photos


Where did I get a dog?

Question: I have a dog now. He's sitting in The Odyssey with his little hat on. Doesn't do much.
I'm pretty sure I didn't buy one of those, and there's no dog in my souvenir list. Where the heck did I get that? What's the trigger?
Comment: Alternate question title: "Why is there a dog in my spaceship?"
Comment: Follow-up question: why does the dog bark silently?
Comment: I believe it comes after you see it/play with it in the mushroom kingdom.
Comment: You can get the dog in Tostarena Town to follow you around after he finds the Moon for you.  Is it the same dog?
Comment: So it wasn't just me ignoring the story then.   Some other people also noticed the dog but don't remember why it's there.  I feel less crazy now.
Comment: @JAL: I was going to say no, but I checked, and it looks like the dog disappears from the Odyssey in kingdoms with a dog moon. That seems to imply it is the same dog following me around. (It's kind of weird, though, because one Toad's dialogue implies the dog in one of the kingdoms is their dog, not mine.) Dunno when the dog starts showing up in the Odyssey, though.
Answer: From the Super Mario Wiki:
"the Dog appears inside the Odyssey after finishing the game at least once..."

Where did I get a dog?


how to change path of iOS file to show project path

Question: To manually include a number of "library" files into  my project, I open my project in xCode. And then I open the "library" folder in finder. Then I drag and dropped from the folder into my project. But now when I go to Buid Phases > Compile Sources I see the path of the files I just copied to be …/download/… instead of /project/.... This is bad because when I push to git, the files aren't passed along and they look red on the computer of anyone else who sync, for the obvious reason that the path specified does not exist on their machines. How do I fix this? As in, when I drag and drop I was expecting for the files to be copied and not just referenced. But they weren't. Is there a simple fix? Note: I mark "copy items into destination group's folder (if needed)".
Also when I open my project in finder, the group that is supposed to have the "library" files isn't in there.
Answer: This is a tricky one. But I can assure you it is human error (well, I think anyway). Do this:
Right click on the group and select "show in finder". You will see that the group belongs somewhere else. So as long as you keep adding to the group, it won't really ever show up in your project. To fix, delete the whole group, type the group by hand, and then try drag and drop again.


tkinter.TclError: image "pyimage3" doesn't exist

Question: I'm having trouble with a function that shows an image for two seconds on screen, and then is destroyed. When the program runs the functions initial call procedurely works fine, but if the function is then called via a button built in tkinter I get an error.
appcwd = os.getcwd()
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
size = str(screensize[0])+'x'+str(screensize[1])

def wlcm_scrn(event=None):
    def destroy_wlcm(event=None):
        wlcm_scrn.destroy()
    global appcwd
    global screensize
    wlcm_scrn = tkinter.Tk()
    file=appcwd+"\\Run_Files\\splash.gif"
    splsh_img = tkinter.PhotoImage(file=file)
    splosh = tkinter.Label(wlcm_scrn,image=splsh_img)
    wlcmh = splsh_img.height()/2
    wlcmw = splsh_img.width()/2
    splosh.pack()
    wlcm_scrn.config(bg='black')
    wlcm_scrn.overrideredirect(True)
    wlcm_scrn.bind("<Escape>",destroy_wlcm)
    wlxym = '+'+str(int((screensize[0]/2)-wlcmw))+'+'+str(int((screensize[1]/2)-wlcmh))
    wlcm_scrn.geometry(wlxym)
    wlcm_scrn.wm_attributes("-topmost", 1)
    wlcm_scrn.after(2000,destroy_wlcm)
    wlcm_scrn.mainloop()

wlcm_scrn() #Call through procedure.

Button that calls the function.
view_img = tkinter.Button(cfrm,text='Show splash image',command=wlcm_scrn)

Error message when called through button command.
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Python33\POS_Solution\Rattle_Hum_POS.py", line 1755, in run_wlcm_scrn
    wlcm_scrn()
  File "C:\Python33\POS_Solution\Rattle_Hum_POS.py", line 34, in wlcm_scrn
    splosh = tkinter.Label(wlcm_scrn,image=splsh_img)
  File "C:\Python33\lib\tkinter\__init__.py", line 2596, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python33\lib\tkinter\__init__.py", line 2075, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist

What is "pyimage3" and why doesn't it exist?
Any help would be apprecaited. Thanks.
Comment: have a look here http://www.daniweb.com/software-development/python/threads/154237/tkinter-problem
Comment: I don't think it's a problem with the file path, as I'm using os.getcwd(), and it works first time around.
Comment: Also the bit by Bennett_1 who states "...the file reference had been incorrect on a previous run." I don't think this is applicable as it worked on the first run, and the file reference doesn't change.
Comment: I can run it multiple times procedurely and it works everytime, so there must be something about calling it as an event on a tkinter button that is causing the issue.
Answer: I found the issue so figured I'd answer myself for anyone who has this issue in the future.
When the wlcm_scrn runs procedurely it is the only window that exists at that point in time, and so it can use tkinter.Tk(). The error arises because the button that calls the function is itself sitting in an active window that is also running as Tkinter.Tk(). So when Python/Tkinter tries to build wlcm_scrn from the button, it's essentially trying to create two windows under root and falling over.
The solution:
Changing line...
wlcm_scrn = tkinter.Tk()

to this...
wlcm_scrn = tkinter.Toplevel()

...stops the error, and the image shows.
I personally am going to have two instances of the function. One called procedurely under Tk(), and one called within the application under TopLevel().
Comment: Whoa, I would have been searching for this for a long time. Instead ... like 30 seconds.
Answer: The PhotoImage method creates an image for the first TK () instance created.
Thus, it seems to have solved to inherit TK () instance by replacing TopLevel ().
This can be solved by specifying the master of the Tk () instance as the option of PhotoImage.
I think this should be changed.:
splsh_img = tkinter.PhotoImage(file=file,master=wlcm_scrn)

Answer: I had been getting the same error, and the above methods work well to fix it, but i also found that if you aren't going to be changing all of this, then you can restart the kernel (in jupyter notebook) or restart your python interpreter
And that should make it work the next time. I am not entirely sure how and why this works tho, but it does and is a simple solution for the time being
Comment: be more specific while answering the question. And never guess the output and post when you are 100% sure otherwise can leave a comment.
Answer: Maybe not for this exact case, but for a similar one, I found that the customary
if __name__ == '__main__':
    wlcm_scrn()  #Call through procedure.

solves the problem as well.
This seems to kill the active window and to create a new one each time you re-call the same module.
Answer: from tkinter import *
import tkinter as tk
window = tk.Tk()

window.title('Learn')
window.geometry("500x500")

text = Label(window, text = 'label here')
text.pack()

photo = PhotoImage(file='C:\\Users\\user\\Documents\\image\\image_2.png')
labelphoto = Label(window , image = photo)
labelphoto.pack()

window.mainloop()enter code here

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: this is one example of code
Root =Tk()
window = Root.Toplevel()

photo =PhotoImage(file='C:\\Users\\user\\Documents\\image\\image_2.png', master= window)

labelphoto = Label(window , image = photo)
labelphoto.pack()

I use "master" in photoImage to specify parent screen . Thank you


PDF/E Writing with Java

Question: ISO 24517-1:2008 Specifies a subset called PDF/E. Its usage is aimed for engineering and technical documentation and the rationale is long term preservation.
My question is, is there a PDFWriter for Java that writes PDF/E compliant documents?
iText doesn't support yet:
"There's no direct support for PDF/E in iText yet. But there's already some functional-ity added that will be mandatory for PDF/UA"
-iText in Action, 2nd ed
Links:
http://www.adobe.com/enterprise/pdfs/pdf-eready-guide-ue.pdf
http://en.wikipedia.org/wiki/PDF/E
http://what-when-how.com/itext-5/pdf-why-and-how-itext-5/
Comment: From the sounds of it the tools able to handle PDF/A would be the first place where I'd look.
Comment: You're linking to a book. And it does *not* seem to be an authorized, public copy of this book. Please don't do that.
Comment: OK, I found another site with same quote though.. Is that grey area?
Comment: Quoting a short passage from a book is legal almost everywhere and definitely more welcome. But the new link still seems to be show a significant portion. Why don't you simply quote that text from the book and leave the link out?
Comment: Yep. I think this question will resolve if and when iText adds the feature. I don't expect much from other implementations.
Comment: Link to copyrighted material removed.
Answer: Is there something specific about PDF/E that you require that is not long-term-preservation?  Is PDF/A (which is about long term preservation) sufficient?  PDF/E seems to be about "engineering workflows" more than long term storage.
If PDF/A is what you need, Docmosis and JODReports are libraries you can use from Java to produce PDF documents including PDF/A.  Just note that PDF/A as a long-term-safe-storage principle disables certain PDF features like external hyperlinks and passwords.

PDF/E Writing with Java


Redirect web server from port 5000 to port 80 on localhost (Fedora)

Question: On Fedora 24, a web server (Node.js) is running (standalone, no apache/others) on port 5000. Trying to making it accessible on port 80.
http://localhost:5000 works
Tried this:
systemctl stop firewalld
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X

iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 5000

http://localhost doesn't work
Tried this
systemctl restart firewalld
firewall-cmd --add-service=http --permanent
firewall-cmd --zone=external --add-masquerade
firewall-cmd --zone=external --add-forward-port=port=80:proto=tcp:toport=5000
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=5000
firewall-cmd --list-all
FedoraWorkstation (active)
  target: default
  icmp-block-inversion: no
  interfaces: wlp3s0
  sources:
  services: mdns ssh dhcpv6-client samba-client https http
  ports: 1025-65535/tcp 1025-65535/udp
  protocols:
  masquerade: yes
  forward-ports: port=80:proto=tcp:toport=5000:toaddr=
  source-ports:
  icmp-blocks:
  rich rules:

Additional info
Tried these
sysctl -w net.ipv4.ip_forward=1
iptables -A FORWARD -j ACCEPT
iptables -A FORWARD -j ACCEPT
iptables -t nat --list

Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:http redir ports 5000
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:https redir ports 5000

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

ifconfig
enp0s25: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536

wlp3s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500

ip route
default via 192.168.1.1 dev wlp3s0  proto static  metric 600
192.168.1.0/24 dev wlp3s0  proto kernel  scope link  src 192.168.1.4  metric 600

For others it just works:
Best practices when running Node.js with port 80 (Ubuntu / Linode)
Running node as root on port 80 works. Note, there's no IPv4:
netstat -tpln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 0.0.0.0:4433            0.0.0.0:*               LISTEN      3977/deluge-gtk
tcp        0      0 0.0.0.0:51157           0.0.0.0:*               LISTEN      3977/deluge-gtk
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      900/postgres
tcp        0      0 0.0.0.0:17500           0.0.0.0:*               LISTEN      3203/dropbox
tcp        0      0 127.0.0.1:17600         0.0.0.0:*               LISTEN      3203/dropbox
tcp        0      0 127.0.0.1:17603         0.0.0.0:*               LISTEN      3203/dropbox
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd
tcp6       0      0 :::4433                 :::*                    LISTEN      3977/deluge-gtk
tcp6       0      0 :::51157                :::*                    LISTEN      3977/deluge-gtk
tcp6       0      0 :::5432                 :::*                    LISTEN      900/postgres
tcp6       0      0 :::17500                :::*                    LISTEN      3203/dropbox
tcp6       0      0 :::34017                :::*                    LISTEN      10532/code
tcp6       0      0 :::5858                 :::*                    LISTEN      30394/node
tcp6       0      0 :::5000                 :::*                    LISTEN      30394/node

Answer: firewall-cmd --add-service=http --permanent
firewall-cmd --add-service=https --permanent
firewall-cmd --add-masquerade --permanent
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=5000 --permanent

#make port forwarding work on localhost
iptables -t nat -I OUTPUT --source 127.0.0.1 --destination 127.0.0.1 -p tcp --dport 80 -j REDIRECT --to-ports 5000

Answer: You should avoid using iptables for things like this, but on Fedora you'd need to setup the firewall appropriately. Also this question has nothing to do with Node.js
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

Related: https://unix.stackexchange.com/questions/39216/cannot-connect-to-fedora-on-port-80
Comment: Thanks, edited to remove nodejs.

# firewall-cmd --add-service=http --permanent
FirewallD is not running

I tried starting it, running these, then iptables again, still doesn't work. Then stopped firewall again.
Comment: Also tried:
firewall-cmd --add-service=http --permanent
firewall-cmd --zone=external --add-masquerade
firewall-cmd --zone=external --add-forward-port=port=80:proto=tcp:toport=5000
firewall-cmd --reload
Comment: What was the solution then?
Comment: see the other answer


Add Embedded Resource to specific path from Assembly compiled at Runtime

Question: public void Compile()
    {
        string OutputPath = Application.dataPath + "/" + Path.Combine(Consts.OutputPath, DLLName) + ".dll";
        Debug.Log(OutputPath);
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5"} });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", "C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll", Application.dataPath + "/" + Consts.IPADLLPath }, OutputPath, true);
        string ManifestPath = Application.dataPath + "/Exporters/manifest.json";
        string ManifestJson = File.ReadAllText(ManifestPath);
        ManifestJson = ManifestJson.Replace("Template", DLLName);
        Debug.Log(ManifestJson);
        File.WriteAllText(ManifestPath, ManifestJson);
        if (csc.Supports(GeneratorSupport.Resources))
        {
            parameters.EmbeddedResources.Add(ManifestPath);
        }
        parameters.GenerateExecutable = true;
        parameters.CompilerOptions = "/optimize -target:library";
        string Code = Consts.BSIPAPluginStarter;
        List<string> Usings = new List<string>();
        Usings.Add(Consts.UsingIPA);
        for(int i = 0; i < scriptCollection.Length; i++)
        {
            string FileStr = File.ReadAllText(Path.Combine(Application.dataPath, scriptCollection[i]));

            int pFrom = FileStr.IndexOf("Using ") + "Using ".Length;
            int pTo = FileStr.LastIndexOf(";");
            //Debug.Log(string.Format("{0}, {1}", pFrom, pTo));

            string result = FileStr.Substring(pFrom-3, (pTo - pFrom)+4);
            Usings.Add(result);
            FileStr = FileStr.Remove(pFrom - 3, (pTo - pFrom) + 5);
            Debug.Log(FileStr);
            //Debug.Log(result);
            Code += FileStr;
        }
        string NewCode = "";
        Usings.ForEach((string Using) => { NewCode += Using; });
        NewCode += Code;
        Code = NewCode;
        Debug.Log(Code);
        if(File.Exists(OutputPath))
        {
            string[] Files = Directory.EnumerateFiles(Path.GetDirectoryName(OutputPath)).Where((string path) => { return path.Contains(DLLName); }).ToArray();
            for (int i = 0; i < Files.Length; i++)
            {
                Debug.Log(Files[i]);
                File.Delete(Files[i]);
            }
        }
        CompilerResults results = csc.CompileAssemblyFromSource(parameters, Code);
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Debug.LogError(error.ErrorText + " " + error.Line + ":" + error.Column));
        EditorUtility.DisplayDialog("Export Succesful", string.Format("Exported To {0}, Remember this doesn't work for quest and will only work on pc, any object that uses the scripts you made won't have any scripts attactched to them!", OutputPath), "OK");
    }

I have my Compile function that does provide me a .dll. But my issue is that manifest.json needs to be at a certain path in the resources.

In this image it's directly at manifest.json but I need it at MyCustomScript.manifest.json.
Example of dll with Manifest.json at correct path

EDIT: I managed to work around it by renaming manifest.json to MyCustomScript.manifest.json
Answer: If you were building using MSBuild, this would be settable in the project file like:
<ItemGroup>
  <EmbeddedResource Include="foo.json">
    <LogicalName>bar.json</LogicalName>
  </EmbeddedResource>
</ItemGroup>

Looking at how MSBuild passes this to csc.exe, it turns into
/resource:foo.json,bar.json

You can also confirm this syntax on the documentation page for the /resource flag.


Why does using a toslink connection protect my sound system from getting interrupted?

Question: This is a follow up question to an issue I was experiencing, mentioned here. I'm really scratching my head on this one, as I assumed this was some sort of voltage issue on the power connection, but it seems it was an issue on the electrical s/pdif (coaxial) connection. I vaguely understand that an optical connection has no ground, so I now suspect the source of the interruption must have been some sort of voltage spike or drop on the ground connection?
A whatthifi article I found mentions

An optical cable doesn't allow noise to pass from source to DAC circuitry like a coaxial can

but it also mentions

And, in our experience, compared to optical, a coaxial connection does tend to sound better. That's because it has greater bandwidth available, meaning it can support higher quality audio up to 24-bit/192kHz. Optical is usually restricted to 96kHz.

Any advice would be greatly appreciated.
Comment: There's no living human that can discern 96Khz and 192kHz sampling rate. Human hearing declines fast above 20kHz, and 96kHz sampling rate is good into the 40kHz-range.
Comment: I'm voting to close this question because it's not about DIY Home Improvement.
Comment: I suspect that bandwidth limitation might just be due to the TOSlink protocol or DAC.  At the purely physical layer, an optical connection is 100% electrically isolated, thus it is unable to transmit any induced electrical noise over the link.  A coaxial cable is still capable of transmitting noise, either induced by source or from electromagnic interference.
Comment: Regarding the bitrate, depends on the equipment, but here's some different opinions about that. Hard claims seem more difficult to track down: https://forum.psaudio.com/t/bandwidth-limit-of-toslink/3592 • https://ayrn.io/toslink-optical-connections-support-24-192khz-audio/ • the latter link is wrong about it being single-mode.
Comment: You don't need anything above 24-bit 48kHz unless you want to attract bats. Seriously, consumer equipment usually won't go higher anyway. Pro gear does, but we're still getting into either 'future-proofing' or 'audiophool' territory, depending on who you listen to.
Comment: @bhrans I thought about that. Is there a more suitable stackexchange for this question a moderator could move it to?
Answer: Because TOSLink is plastic fiber optic streaming data, and thus immune to electromagnetic interference.
Unlike copper data transmission.
We networking folks LOVE fiber optic for that advantage, and while TOSLink is kinda low on the scale of data networking with fiber optics, it still has that advantage.
Obligatory TOSLink note - if someone tries to sell you a gold-plated TOSLink device, tell them to find another sucker. TOSLink being PMMA plastic fiber the only reason to gold-plate anything is to get AudioPhools to waste money on useless crap.
Comment: I did a little further research on this and while I think this is what you are implying, explicitly, it is likely the power fluctuations were dumping EMI to the ground connection, which in turn caused interference on the coaxial connection. Since toslink has no ground connection, it is impervious.


Django filter with distinct and values issue

Question: I have the following code:
>>> y = Menu.objects.filter(level=1).values('name').distinct()
>>> y
[{'name': u'Desserts'}, {'name': u'Wings'}, {'name': u'Biriyani'}, {'name': u'Starters'}, {'name': u'Desserts'}, {'name': u'Starters'}, {'name': u'Biriyani'}]

It is not giving me a distinct result set. How can i achieve distinct values?
According to both the solutions, i got the error:
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/query.py", line 138, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__
    self._fetch_all()
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/query.py", line 1217, in iterator
    for row in compiler.results_iter():
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 794, in results_iter
    results = self.execute_sql(MULTI)
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/Users/abhishek.yeruva/workspace/myreps/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("myapp_menu"."name") "myapp_...

Answer: Use values_list instead of values and set flat parameter in values_list:
y = set(Menu.objects.filter(level=1).values_list('name', flat=True))

Pass your value list to set function and it create a set with unique values like Joey Wilhelm write in comment.
Comment: this worked for me: y = Menu.objects.filter(level=1).values_list('name', flat=True).order_by('name').distinct()
Comment: this is still not giving me distinct values... i got this: [u'Desserts', u'Wings', u'Biriyani', u'Starters', u'Desserts', u'Starters', u'Biriyani']
Comment: same error i mention to Joey with the distinct('name')
Comment: If you want to use values_list, you would want to do something like:  `y = set(Menu.objects.filter(level=1).values_list('name', flat=True))`. Note, however, that this will not give you a QuerySet, if that is what you are desiring.
Answer: Alternative to Dima's solution, if you are using PostgreSQL, you can specify what field to perform the distinct query on, as described in the .distinct() documentation. For example:
y = Menu.objects.filter(level=1).distinct('name').values('name')

Comment: i ll post the traceback in the question
Answer: See the note here-- if you are using order_by the field you are ordering on will be included in the DISTINCT. You don't show an order_by in the query but if you have one set in the Meta class of your Menu model it will still apply.
Comment: oh fantastic... this worked for me: y = Menu.objects.filter(level=1).values_list('name', flat=True).order_by('name').distinct()


java equivalent of Delphi NOT

Question: In Delphi I can do the following with a boolean variable:
If NOT bValue then
begin
  //do some stuff
end;

Does the equivalent in Java use the !?
If !(bValue) {
  //do some stuff
}

Answer: You're close; the proper syntax is:
if (!bValue) {
  //do some stuff
}

The entire conditional expression must be inside the parenthesis; the condition in this case involve the unary logical complement operator ! (JLS 15.15.6).
Additionally, Java also has the following logical binary operators:

JLS 15.22.2 Boolean Logical Operators &, ^ and |

casually "and", "xor" and "or"

JLS 15.23 Conditional-and && and JLS 15.24 Conditional-or ||

the much more frequently used short-circuiting "and" and "or"

There are also compound assignment operators (JLS 15.26.2) &=, |=, ^=.

Other relevant questions on stackoverflow:

Shortcut "or-assignment" (|=) operator in Java
Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=)
What's the difference between | and || in Java?
Cleanest way to toggle a Boolean variable in Java?
Getting confused in with == and = in "if" statement

There are plenty of similar questions on stackoverflow due to accidental boolean assignment instead of comparison
You never need to write == true and == false

Omit explicit comparison with true and false
use ! when necessary
Answer: Yes, but inside the bracket:
if (!bValue) {
}

You'd normally not use any sort of data type prefix in Java as well, so it would more likely be something like:
if (!isGreen) { // or some other meaningful variable name
}

Comment: Thanks!  My variable is actually IsFYE so it is meaningful!
Comment: BTW: Using data type prefixes isn't common practice in Delphi either. More common are prefixes that identify the scope of a variable which I generally find much more useful, too.
Answer: if (!bValue) {
    // do some stuff
}

java equivalent of Delphi NOT


Probability of a substring in two different strings

Question: Say you have a 10 digit string, where A-Z and 0-9 are all allowed. Within that string, you have the substring "DAD." I'm trying to find the probability of getting a second randomized string with the same parameters as the first (10 digits, A-Z and 0-9 allowed) containing that same substring. In other words, I guess I'm wondering about the probability of that substring occurring twice in two randomized strings with the exact same parameters.
Not sure where to start with this really, can someone point me in the right direction?
Comment: Do every A-Z and 0-9 values appear independently with the same probabilities for any character in your string? In the end you say that you want the probability of the two strings to contain the same substring. Do you know the substring? Or any substring of any size? Only 1 substring (consecutive characters) in common? You need to provide more details
Comment: @MaxFt The substring is "DAD." Or another substring that contains one character twice and another once. That's the only substring that needs to be in common. And yes, the values appear independently with the same probabilities for any character.
Comment: Do you know the substring you are looking for in the two strings beforehand. Or does it just need to contains one character once and another twice in any order?
Comment: The characters in the substring need to be in the same order. So if the first substring is "DAD," the second one needs to be "DAD." If the first one is "DDA," the second one needs to be "DDA."
Comment: Ok got it. Thanks for the clarification. Interesting problem indeed
Comment: This is going to depend on the substring.  There are five different three-character patterns, depending on which characters, if any, are repeated: xyz, xxy, xyx, xyy, xxx.  This compares with two two-character patterns, and twelve, I think, for four characters.  It's not obvious to me that there is going to be any simple order-independent property of the substring that will permit an easy calculation—e.g., xxy will have a different probability from xyx.  There may be something applicable in DeBruijn graphs.
Comment: @BrianTung he said that one character appears twice and the other appears one time. We are just left with 2 cases: DDA, AAD structure that does not allow overlap and DAD structure that allows overlap. (see discussion in my answer)
Answer: Number of possible string: $36^{10}$
The substring you look for have to start at the 1st,2nd,3rd,4th,5th,6th,7th or 8th character and the 7 other characters can be anything. Thus, $8\times 36^7$ favorable outcomes.
Note that with this method when the substring appears $n$-times in the string the outcome it will be counted $n$ times; once for each starting points of each instance of the substring.
On the other hand consider a string where the substring appears at least $n$-times in the string, this string also appears once in the set of string where the substring appears at least $n-1$-times. Call $n_i$ the number of strings containing at least i instances or the subtring:
#favorable outcomes = $n_1 - \sum_{i>1} n_i$
Now let's compute $(n_i)$ for the two possible structure of substrings (one allowing overlapping, the other does not):
Case with structure not allowing overlap (DDA,ADD):
$n_3=3*36$
3 Triplets of starting character possible: (1,4,7);(1,4,8);(2,5,8)
$n_2=10*36^4$
4+3+2+1 = 10 Couples of starting character possible: (1,4);(1,5);..(1,7);(2,5);...;(2,8);...;(5,8)
Probability = $\frac{8\times 36^{7} - 10*36^4 - 3*36}{36^{10}} $
Cases with structure allowing overlap (DAD):
$n_3=22*36$
4+3+2+1+3+2+1+2+1+1=22 Triplets of starting character possible: (1,3,5);(1,3,6);...;(1,3,8);(1,4,6);...;(4,6,8);
$n_2=21*36^4$
6+5+4+3+2+1 = 21 Couples of starting character possible: (1,3);(1,4);..(1,8);(2,4);...;(2,8);...;(5,8)
Probability = $\frac{8\times 36^{7} - 21*36^4 - 22*36}{36^{10}} $
Comment: Double counting is a particularly problematic with this string because of overlaps.  You could have DADADADADY which contains the substring 4 times.
Comment: Arf you are right. And the overlapping possibilities depends on the structure of the substring... DDA or ADD VS DAD the 2 cases gives different overlap possibilities
Comment: Looks like you ended your comment prematurely.  What is the rest of the sentence?
Comment: I finished the sentence and edited my answer accordingly sorry. For structure like DAD I would to have to also add the overlapping scenario in the cases I substract. It is easily feasible as long as I am careful but I am even more interested in transforming the problem rather than brutally counting the cases now.


Outputting spliced version of input

Question: #include <iostream>
#include <string>

using namespace std;

int main()
{
  char name[256];
  cout << "Enter your name: ";
  cin.getline (name,256);

  for(int i = 0; i < 50; i++)
  {
    cout << name[i];

    if (name[i] == '\n')
      break;
  }

  cout << endl;
  return(0);
}

Enter your name: My name is Sean
once I do that it outputs "My name is Sean" but then a bunch of nonsense crazy symbols after that.
How come it doesn't stop after 'n' in Sean? Since there's a '\n' character there. Or at least I would think.
All, I want is to output every character in name one symbol at a time, and stop when it gets to the end of the line so that it doesn't have to go to 256 when the array is actually much smaller
What's wrong with my code?
Comment: Tag this homework please if it is.
Answer: cin.getline reads the newline (or whatever you specify as the delmiter) out of the input buffer, but does NOT include it in the string that's produced, so you're reading past the end of the data that was read until you encounter the next byte that happens to contain the value that corresponds to a new-line (typically 10).
It's a lot easier to just write it all together: cout << name;
Answer: From documentation:

Characters are extracted until either
  (n - 1) characters have been extracted
  or the delimiting character is found
  (which is delim if this parameter is
  specified, or '\n' otherwise). The
  extraction also stops if the end of
  file is reached in the input sequence
  or if an error occurs during the input
  operation.
If the delimiter is found, it is
  extracted and discarded, i.e. it is
  not stored and the next input
  operation will begin after it. If you
  don't want this character to be
  extracted, you can use member get
  instead.

Outputting spliced version of input


Is possible to access ATTR for Perl packages without defining a getter?

Question: I am currently working on a Perl 5.8 project.
I have package that looks like:
package Foo::Bar;

use strict;
use warnings;
use Class::Std;

our @EXPORT_SAFE = qw(Class::Std);

my %baz :ATTR;

sub BUILD {
  my ($self, $ident, $args) = @_;

  $baz{$ident} = $$args{something};
}

I am not exposing baz with any getter, but I would like to fetch it's content for unit testing purposes. There is any way to do it in Perl?
e.g. in Ruby you can some_instance.instance_variable_get("@#{name}")
Thank you very much in advance
Comment: Perl 5.8. From 2002! Why do people do this to themselves?
Answer: TL;DR
The answer in the general case is "it depends (but probably)".
The answer in your case is "no".
Detail
There is no fixed way to implement classes and objects in Perl. In most cases an object will be a blessed reference to a hash. In those cases, you could simply treat the object reference as a hash reference and look up the key directly. So, code like this:
my $baz = $obj->{baz};

However, you're not using the most common approach to building Perl objects, you're using Class::Std. And Class::Std does things rather differently. Class::Std uses an approach called "inside-out objects" which was popularised by Damian Conway in Object Oriented Perl and which was very fashionable for a while about twenty years ago.
In normal objects, you have a hash for each object. The keys are the attribute names and the values are the attribute values. With inside-out objects, each attribute has its own hash. The keys are the stringified references to an individual object and the value is the attribute's value for that object.
In effect, the "standard" approach is:
$object{attr} = value;

And the inside out approach is:
$attr{object} = value;

One of the big reasons why people liked inside-out objects is that the attribute hashes can be lexical variables stored in the class's source code. And that means they are truly private and cannot be accessed from outside of the class - except by using the provided accessor methods. Which is great if you want to force Perl to implement a far stronger kind of encapsulation. But terrible if you want to break through that encapsulation in the way that you do here.
So, no. In your case, you can't do this.
Comment: Actually I tried dump the content of my instance and I got something like `bless( do{\(my $o = undef)}, 'Foo::Bar')` and when I try to to access the `$obj->{baz}` I get a not an HASH reference error. Thank you for the explanation then!
Comment: @mabe02: Yeah, inside-out objects contain no data. That's confused me a few times in the past :-)
Comment: And therein lies one the problem with them: They make debugging harder. (Yes, it's not necessarily a major problem. After all, an XS-based object might be similar in appearance.)
Answer: Class::Std could easily provide ->instance_variable_get, at least for variables that were given a name.[1] But it doesn't.

In the absence of something provided by Class::Std, you could add the following to your class:
use Carp qw( croak );

sub instance_variable_get {
   my ($self, $name) = @_;

   my $pkg_glob = do {
      no strict qw( refs );
      *{ __PACKAGE__ . "::" }
   };

   exists($pkg_glob->{$name})
      or croak("Unknown attribute $name");

   my $hash = *{ $pkg_glob->{$name} }{HASH}
      or croak("Unknown attribute $name");

   return $hash->{ident($self)};
}

Note that this requires using our instead of my for the hashes.
This will allow you to use
$some_instance->instance_variable_get('baz')

Of course, if you're using our for the hashes, you could also use
$Foo::Bar::baz{ $some_instance->ident }

Currently, :ATTR( :name<...> ), :ATTR( :init_arg<...> ), :ATTR( :get<...> ) and :ATTR( :set<...> ) provide a name for the attribute, though these all have other effects as well.
Comment: it looks very promising. I am going to check it tomorrow morning.


Is an Interior French Drain Necessary?

Question: We just had 12 hours of straight rainfall in SE PA, with like one total hour of respite. After all that, my basement looks as follows:

There is a crack by the cellar door that is leaking:

I just had new gutters put on and they work swell - but there's still a lot of pooling around the exterior of the house, the slope is negative and there's a literal trench about 4 inches deep running around the perimiter of the house - please note this is a twin, so I only have control over one side of the house.
I tried grading the soil myself in the corner where the cellar was leaking but nothing helped. Here it is before I sloped it down. You can sort of see the rest of the side of the house.

I had a waterproofer come out and of course try to sell me on an interior French drain. He said that it would solve my problems. While true, I still feel like it would make more sense to actually have the soil properly graded away from the house and get the sump pump upgraded and backed up. I could literally see pools of water along the side of my house. I showed that to him and he just said "the water isn't coming into the basement where this water is pooling". He said a rising water table isn't going to be fixed by sloping the outside soil away from the house.
I could use some advice. I'm really thinking the grading and the sump work will be a better solution, even though there are 2 cracks where water wants to come in from, it's a stone foundation, I fear epoxy injection would blow that out. Not ideal.
Comment: I would say that the first thing to do is try to fix up that crack and see what happens. Grading outside would be beneficial, but whatever water gets to the door, which seems to be at the bottom of steps, will get in through the cracks there.
Comment: "How should I seal this crack in my foundation?" would make an excellent stand-alone question, along with some good close-up photos of the crack in question. It looks like the wall is _probably_ block with a parge coat on it - you may want to investigate that some to provide that kind of detail in your new question.
Comment: Firstly, if you have a sump you don't have a French drain. Those are simply gravity drains that "daylight" somewhere downslope. Secondly, yes... exterior grade is your first line of defense and may well resolve the problem, _if_ you don't have the high water table you were warned about. However, I'm reluctant to post an answer as it would be largely speculative. You'll know when you try.
Comment: @FreeMan Is there a way to do that from the inside? Or does that require digging down from the outside? What kind of sealant should I look to use? Or should it be filled with something? I think this part of the house is cement and not stone like the rest of the foundation. But I'm not sure.
Comment: As should be clear by now grading is necessary but not sufficient to solve the problem. The issue in much of southeast PA is the high water table - I'm familiar with it. The right answer is a good water mitigation system moving the water to a sump pump. It's expensive but the right way to go.
Answer: Grading your slope is unlikely to fully fix your issue.
Grading a slope around your foundation is relatively easy and takes few materials, so it's usually recommended to try especially if you have a negative slope. Unfortunately it is not a fix-all because water can travel through soil especially in heavy rainfall or high water tables. Standing water near your foundation is a recipe for disaster and besides just letting water in through cracks and improper seals, will actively make the cracks worse through erosion and freezing.
The other side of this "twin" is likely to have the same issues as you do so enlisting their help (especially with the recent rainfall making this top-of-mind for you both) is likely to yield better results.
That said, there are two primary ways to handle water-at-foundation issues and the one primarily used in new construction is best done at the time the foundation is poured. Drain tile is buried around the base of the foundation wall and connects to pipes running under the floor into a sump pit. As water seeps through the soil next to the foundation, it can easily enter these pipes and flow to the sump, which activates when it reaches a certain level and pumps a few gallons of water to a drain outside. Water can migrate through concrete so the exterior of the wall is typically sealed to keep moisture outside the concrete foundation wall.
The other way which your waterproofer suggested is to deal with the water once it's already inside by using a drain. Cutting shallow channels or negative slopes to a floor drain or sump pit can also route the water, but if the water is pooling like this you will definitely have high moisture and humidity so you'll need to take that into account when storing items in the basement and will be unable to easily finish that space.
If I were you I would look into options to seal the exterior foundation (which requires removing a lot of soil around the foundation wall, in my experience) and fix the crack in your photo. If you do nothing else, this will increase the pressure from the water table and cause your foundation to crack, so you also need to route the water somewhere. An exterior french drain may work if you have the slope and gravity to route water away from the house; otherwise you need a pump - and since you're in a freeze-prone area, that pump should be inside in a pit. While the dirt is excavated away from the foundation would be a great time to install drain tile and plumb to a sump pit, and you can finish by putting the soil back and grade away from the house. This will be expensive but has the best chance of preventing further foundation damage. Your waterproofer consultant has probably already suggested some or all of these steps.
Answer: This is such as academic problem!  Is it a rising water table, it is an underground stream, is it bad grading from the house, or is it faulty construction?  I agree with you that the least expensive, most obvious solution should be tackled first.  This spring, have a ton or two of brown dirt delivered to your house, and have the driver dump it near the problem site ("a ton" is simply industry talk for a pickup truck full of dirt).  It may cost you $100 (maybe more, I did this 30 years ago).  If needed, prep the site by laying down plastic sheeting (this will make the finished product very sanitary looking).  Along your your bad grading, also lay good quality plastic sheeting, extending coverage out about five feet from the house, and rising as high as the window wells.  Then, use a wheelbarrow and shovel, move all the dirt against the side of the house, as high as the window wells, and extending out to cover all of the sheeting.  When you are through, get a bag of quality grass seed (shade for unlit areas), and rake it in.  Pat it down lightly, and water it every morning and evening.  It's important for grass to grow because the roots deflect water away from the house (the reason why excavated, exposed land turns into a landslide during a rainstorm is because it is devoid of roots).  Overfill the area about a third, because gravity will pull the ground down that far within a year.  Next spring, you may need more dirt, and if so, repeat the process.  This is not a miracle cure.  However, it will eliminate most (90%) of the problem.  On the inside, find the lowest side of your basement and install a sump pump.  This is another do it yourself job, and it's not that tough.  Buy a black plastic drum (with no holes) and lid at the Home Depot, and rent a full sized jackhammer.  Take the lid of the drum, use a black marker and trace a circle on the floor in the corner of the basement (6" to a foot from the walls), and jackhammer out the floor.  Buy a dozen 5 gallon HD buckets, fill them up, and haul everything upstairs (it's really not that bad; the buckets are cheap, and beyond the concrete, most of your haul will be dirt excavated with a garden hand shovel.  When your bucket fits in nice and level with the ground, screw the lid back on.  You will want to do this, because the next step calls for a bag or two of mortar to fill around the sides of your sump.  When the cement dries, you can unscrew the top and have a perfectly placed well, with a lid that fits perfectly on top.  However, prior to mixing the mortar, backfill the area with a bucket or two of soil (lessening the need for cement).  Next, buy a 1/2 horsepower sump pump (Liberty pumps are the best; the ball is designed not get stuck open and run forever).  Then connect the pump with pvc piping to connected to a drainage system on the outside of the house (if possible, deflect the water 20 feet away from the foundation).
Next chisel out the cracks in your basement walls, and fill them in with hydraulic cement.  You can even paint the walls with waterproofing paint, but the stuff just doesn't work (I would spend the money and do it anyway).
Last, look where all the water comes in from, and if necessary, rent that sledgehammer again and chisel out the floor next to the wall, only deep and wide enough for a 2x4 to fit in, flush with the floor. Chisel out the whole corner of the wall, and then down to the sump pump.  Secure your 2x4's (pros in this business say, "use motor oil and rub down the boards.  This way the cement won't stick to them when it dries."), and install shims between the wall and the 2x4's (when your mortar dries, you pull out the shims, and then pull out the 2x4's; both the shims and the oil prevent the 2x4's fro getting stuck).  Finally, buy a few bags of mortar and trowel them in the long gap between the 2x4's and the basement floor.  Give the floor a nice finishing touch, and you will have A+ french drains.  If you have the ambition, you might do all four walls, and for a cost of $100 to $200, you will save yourself a whole lot of money.
French drains are nice, but you should have them hooked up to a sump pump to carry water away.  Otherwise, sitting water can be a bad health hazard.
You have now tackled this problem from the top down, and from the easiest to the hardest work.  It's not bad.  It's a project that may take you 3 to 4 years, if you are lazy, like me.  Never believe talk like underground springs or a rising water table, because that stuff is self defeating and is just not true (if you have an underground spring below your basement, your floor would show it, not the walls, and a rising water table only occurs in super poor drainage areas, or with houses built on clay).
Comment: A paragraph break or 2 (just hit the `` key twice) will make that massive wall of text _much_ easier to read.

Is an Interior French Drain Necessary?


How to use Laravel Eloquent from raw php file in laravel project

Question: I am currently invoke a raw php file from MySQL trigger.
It invokes that php file by passing some parameters.
In php file, I noticed I can't use Laravel Eloquent.
Is there anyway to use Eloquent queries in the raw php file?
I think I can call a function of controller by routing in here raw php file.
Is there any resoultion for this problem.
Thanx
Answer: If you can call a raw PHP file, then you can also wrap its content into an Artisan command which will automatically use Laravel (and Eloquent of course)
<code>php artisan yourCommand arg1 arg2 ...
</code>
Comment: Thank you for your advice.
But what should I do in that PHP file?
I need to run that .php file from trigger.
But in that php file, I couldn't use the Model or Eloquent to query database.
Is there anyway to use Eloquent?
Thanks
Comment: for example, I can't use this Eloquent query
$email = Email::where('id', $id)->first();
$id comes from mysql trigger
Comment: `artisan` is nothing more than a PHP file, you just need to replace your current call from the trigger
Comment: Depending on what your trigger does, you could also use Eloquent observers instead which are much cleaner https://laravel.com/docs/7.x/eloquent#observers


If $(X_n)$ is a martingale, prove that $(X_{n\wedge N})_n$ is a martingale, where $N$ is a stoping time

Question: Let $(\Omega ,\mathcal F,\mathbb P)$ a probability space and $(X_n)_{n\in\mathbb N}$ a martingale w.r.t. the filtration $(\mathcal F_n)$. Let $N$ a stopping time on $\mathbb N$. Prove that $(X_{N\wedge n})_n$ is a martingale w.r.t. $(\mathcal F_n)$.
Attempts
I have to prove that $$\mathbb E[X_{N\wedge (n+1)}\mid \mathcal F_n]=X_{N\wedge n}.$$
So let $F\in \mathcal F_n$. Then, $$\mathbb E[\mathbb E[X_{N\wedge (n+1)}\mid \mathcal F_n]\boldsymbol 1_F]=\mathbb E[\boldsymbol 1_F X_{N\wedge (n+1)}]=\sum_{p=0}^\infty\mathbb E[\boldsymbol 1_FX_{N\wedge (n+1)}\mid N=p]\mathbb P\{N=p\}.$$
Q1) Is it true that $$\mathbb E[\boldsymbol 1_FX_{N\wedge (n+1)}\mid N=p]=\mathbb E[\boldsymbol 1_FX_{p\wedge (n+1)}]\ \  ?$$
If yes, then $$\sum_{p=0}^\infty\mathbb E[\boldsymbol 1_FX_{N\wedge (n+1)}\mid N=p]\mathbb P\{N=p\}=\sum_{o=0}^\infty \mathbb E[\boldsymbol 1_FX_{p\nabla (n+1)}]\mathbb P\{N=p\}=\sum_{p=0}^n\mathbb E[\boldsymbol 1_FX_p]\mathbb P\{N=p\}+\sum_{k=n+1}^\infty \mathbb E[\boldsymbol 1_FX_{n+1}]\mathbb P\{N=p\}.$$
Since $(X_n)$ is a martingale, $$\mathbb E[\boldsymbol 1_FX_{n+1}]=\mathbb E[\boldsymbol 1_F\mathbb E[X_{n+1}\mid \mathcal F_n]]=\mathbb E[\boldsymbol 1_FX_n]$$
Q2) How can I continue ?
Answer: Note that
$$
\begin{aligned}
E(X_{N\wedge n+1}| \mathcal F_n) &= E(X_{N} 1_{N\leq n}+X_{n+1} 1_{N\geq n+1}| \mathcal F_n)\\
&= 1_{N\leq n} E(X_{N} | \mathcal F_n) + 1_{N\geq n+1}E(X_{n+1}| \mathcal F_n)\\
&= 1_{N\leq n} X_N + 1_{N\geq n+1}X_n\\
&= X_{N\wedge n}
\end{aligned}$$
Comment: In your second-to-last line, the first term should be $1_{N\leq n}X_N,$ which is easy to see if you note $1_{N\leq n}X_N \in \mathcal{F}_n$ in the first line.
Comment: @BrianMoehring thanks for catching the typo !
Comment: as the OP asked, does $\mathbb E[X_N\mid N=p]=\mathbb E[X_p\mid N=p]$ or $\mathbb E[X_N\mid N=p]=\mathbb E[X_p]$ ? I would say yes, but I'm not sure.
Comment: @user659895 $\mathbb E[X_N\mid N=p]=\mathbb E[X_p\mid N=p]$ holds when $N$ and the $X_i$ are independent, otherwise I don't think it's true (write the expectations in terms of integrals w.r.t the appropriate regular conditional distributions).
Comment: If $X_i$ and $N$ are independents, $\mathbb E[X_p\mid N=p]=\int_{\mathbb R}xf_{X_p\mid N=p}(x)dx=\int_{\mathbb R}xf_{X_p}(x)dx=\mathbb E[X_p]$. But now, what would be $\mathbb E[X_N\mid N=p]$ ? Is it $\int_{\mathbb R}xf_{X_N|N=p}(x)dx$ ? If yes, what is $f_{X_N|N=p}(x)$ ? the fact that $N$ is a r.v., I don't see what could be $f_{X_N}$ or $f_{X_N|N=p}$. thank you.
Comment: @user659895 Let $Y=(X_1,X_2,\ldots)$ and note that $$E(X_N|N=p) = E(\sum_k X_k 1_{N=k}|N=p) = \int \sum_k x_k 1_{N=k}dP_{Y|N=p} (x)= \int x_p dP_{Y|N=p} (x)$$ while
$$
E(X_p|N=p) = \int x_p dP_{X_p|N=p} (x_p)
$$
The problem is that the final integrals may not be equal (they are when the $X_i$ and $N$ are independent).
Answer: My favourite proof relies on the fact that $M_{N \wedge n} - M_{N \wedge (n-1)} = \mathbb{1}_{N \geq n} (M_n - M_{n-1})$. Then, note that $\{ N \geq n \} = \{ N  \leq n-1\}^c \in \mathcal{F}_{n-1}$. Therefore, $\mathbb{1}_{N \geq n}$ is a predictable process so:
\begin{equation}
\mathbb{E}\left[M_{N \wedge n} - M_{N \wedge (n-1)} | \mathcal{F}_{n-1} \right] = \mathbb{1}_{N \geq n}\mathbb{E}\left[M_{n} - M_{n-1} | \mathcal{F}_{n-1} \right]=0.
\end{equation}


Why is restarting client IE changing the username logged in IIS?

Question: I have an ASP.NET WebForms application. Some of my users reported that they see their username in "domain\username" format. When they close their IE and open it up back, username is shown as "username". Application shows "username" mostly. However, it shows "domain\username" every once in a while (I couldn't find the pattern).
What is the reason of this behavior?
Environment:

Windows Server 2008 R2, IIS 7
.NET Framework 4.5.2
Anonymous and Forms authentications enabled. Others disabled
Application pool idendity: "ApplicationPoolIdentity"
In application pool settings, "Enable 32-Bit Applications" is "True"
In application pool settings, "Managed Pipeline Mode" is "Integrated"
Internet Explorer 11 is used in client
Variable I use to get usernames: User.Identity.Name
Comment: Can you put the code you are using to display the username within your application in your question please?
Comment: Added (User.Identity.Name). Thanks!
Answer: SiteMinder was creating the issue. Once it's installed in your web server, it may change your application's cookies even though your application is not protected by SiteMinder.


Dijkstra step-by-step

Question: I've been following Dijkstra's algorithm step by step from http://www.ifp.illinois.edu/~angelia/ge330fall09_dijkstra_l18.pdf
However with my own example, I don't find the shortest path if I stop as soon as I reach the destination node.
I'm going to look for the shortest path from A -> E as below:

And I traverse as follows:

This gives me the shortest path of A->F->E which is incorrect (the shortest path is C->D->E).
The difficulty being that I never inspect D.
But I've read (not least in the link above) that you can stop inspecting nodes as soon as you reach the destination. How is this true?
Comment: The distance is calculated correctly. How did you arrive to the path itself?
Comment: @n.m. The distance is not correct, the shortest distance is 11.
Comment: The calculated distance is A-F-E which is 17, the correct should be C-D-E which is 11
Comment: @Henry yeah I see now. The power of large images on a phone.
Comment: Sorry for using the images. I also found it problematic to use text for issues like this and don't have an ideal solution to that.
Answer: You stopped too early. Continue the algorithm until E is selected as the current node.

Dijkstra step-by-step


Running quick-start plunker on chrome browser?

Question: I am trying to run angular2 quickstart example of plunker in my local environment.
For this, I followed these steps-

Download all files from https://angular.io/resources/live-examples/quickstart/ts/plnkr.html into local folder on my machine.
Double-click on index.html to run application.

this way, I am able to run application on Firefox. but I get an error on chrome-

firstname.lastname@example.com?main=browser:101 XMLHttpRequest cannot load
  file:///C:/Adi/angular2-RC5-plunker/app/main.ts. Cross origin requests
  are only supported for protocol schemes: http, data, chrome,
  chrome-extension, https, chrome-extension-resource.

How do I run this quick-start application on chrome browser successfully?
chrome error screenshot
Comment: The quick start has a node lite server built into it. I would recommend using this instead. https://github.com/angular/quickstart
Comment: **Unbelievable** that there's no way to to run a project when you have the complete source code. What's missing? Is the configuration missing? Are the dependencies missing??? In Java, for example, there's a single file, pom or gradle, that provides you with all the configuration/dependencies needed to run a project. What's missing in Angular 2???
Comment: Also, strange that this runs on Firefox but not on Chrome. I thought Angular requires some server side functionality for part of it's core components. Though I would be really glad it wasn't the case. See [Why does Angular require a server in their tutorials?](http://stackoverflow.com/q/31624686/435605).
Answer: Combining steps to fix with the process explanation. Follow the numbered fixes to fix the configuration.
* Solution based on npm as used in the official Angular 2 guide.
Angular 2 plunker link redirected me to an Angular 2 QuickStart example (which is different from Plunker's Angular 2 template - FYI).
I downloaded Plunker's project, as Adi99 did.
I then tried following the steps in Angular's QuickStart setup but failed on npm install.
Error: ENOENT: no such file or directory, open '/home/alik/Dev/help2/package.json'.
Fix step 1: Download package.json from Angular 2 QuickStart source code, put it in the root's project folder and change in the file src with ..
Running npm install now passes successfully, probably downloading all the necessary dependencies.
The next step in the QuickStart tutorial is to run npm start which fails on error TS5057: Cannot find a tsconfig.json file at the specified directory: './'.
Fix step 2: Download tsconfig.json from Angular 2 QuickStart source code and put it in the root's project folder..
Running npm start now passes successfully, creating the server and opening a browser page with the address http://localhost:3000/, rendering Angular 2 code successfully with the message:

Hello Angular

Hope this helped and Angular team :) will make the initial configuration easier. It's a bad architecture to have lots of configuration files. Hard to understand what's needed, why and how to change it.
For example, in Angular's QuickStart source project, there are 10 configuration files: bs-config.e2e.json, bs-config.json, karma-test-shim.js, karma.conf.js, package.json, protractor.config.js, tslint.json, src/systemjs.config.extras.js, src/systemjs.config.js, src/tsconfig.json


Permanently hidden warning from Scalac parsing Java code - compiler bug?

Question: The scalac Java parser is taking objection to my Java code
imported `Entity' is permanently hidden by definition of object Entity in package domain    Asset.java

This seems to be a collision between an import and a class with the same name in the package being compiled.
In my package I have a class
package iMP2020.domain;

public interface Entity {
    public Serializable getId();
}

with the same name as an imported class from a different package
package iMP2020.domain;
import javax.persistence.Entity; // compiler warning

@Entity
public class Asset {

where it is complaining about the import. Javac is quite happy. Note that I don't have to reference my version of the class- just its existence is enough to trigger the warning on the import.
I can fix this by removing the import and explicitly referencing @Entity, but is it a bug in the compiler?
Comment: Whether or not it's a bug, why are you using the Scala compiler to compile Java code instead of the Java compiler?  Regardless of whether javac or scalac is not living up to the Java spec (or whether the behavior is not covered by a spec), if you want the javac behavior, use javac?
Comment: Because scalac parses Java source in order to deduce the type signatures so that we can have circular dependancies between Java and Scala - http://www.codecommit.com/blog/scala/joint-compilation-of-scala-and-java-sources
Comment: In other words, "I have an unresolvable circular dependency between Java and Scala, but somehow I can compile this successfully with javac anyway, which is how I know that javac doesn't complain?"  I don't know whether it's a bug or not, but either way, it's good that you have a workaround.
Comment: Don't know if it is a bug, but given that it is a warning and not an error, the Scala compiler does not violate Java specification.
Comment: @Rex Actually I don't have any unresolvable dependencies, so that javac compiles this just fine.
Comment: Then there isn't any reason to have scalac parse it, which is probably the best workaround (since you get bytecode as well as a symbol table out of javac).
Comment: @Rex - I didn't ask how to get rid of the warning, I asked if it is a bug! It arose adding the Scala nature to an Eclipse project - which evidently sets scalac to work on all my .java sources.
Comment: Even if it's a bug in (Sun's) javac, you probably want scalac to work exactly the same way, so you could file a bug report.  I'd guess that it's a pretty low priority, however.
Comment: It emphatically isn't a bug in javac - it understands that there is no conflict. But scalac doesn't. I'll take it off to the scala mailing list.
Answer: I don't seem to be able to reproduce this except with the Scala Eclipse plugin, so I'm going to wait for that to stabilise before coming to a conclusion.
Comment: try to "import javax.persistence" then use it as javax.persistence.Entity in your code.
Answer: You have two Entity references, one for your interface, and another one for javax.persistence.Entity.
Try to replace the second one with the full qualified name, removing the import:
package iMP2020.domain;

public interface Entity {
    public Serializable getId();
}

and
package iMP2020.domain;

@javax.persistence.Entity
public class Asset {

Answer: I don't think it is a bug.
It doesn't make sense for an import to have the same name as a package member.
Comment: Well it does make sense if I have a class in another package with the same name as a class in my package. Surely javac should be the arbiter here, and it doesn't issue a warning.
Comment: @Duncan, Sorry, what I meant is that it doesn't make sense for the compiler to allow you to use 2 classes with the same name.  It could be that javac expects you to use the fully qualified class name to reference the import.
Comment: Note that I don't have to reference the class in the current package. Just its existence is enough to trigger the warning on the import. In the case of the code above, javac only considers the explicit import and does not give a warning. Scalac complains.


Why is semi-norm special and preferred?

Question: One difference between semi-norm and norm is:
"It is possible for $\|v\| = 0$  for nonzero v, $\|\cdot\|$ being semi-norm"
I see some papers, and they use semi-norm directly.
Why is semi-norm better than norm?
Any simple example or concrete example?
Comment: Seminorms allow us to maintain distinctions between points that are not distinguished by the seminorm. This comes up in certain situations, for example if $f$ and $g$ are measurable functions and $f=g$ a.e. then $\| f - g \|_1 = 0$ even if $f \neq g$. It is often convenient to define a seminorm and then quotient out all points which have seminorm zero. Since in the new space all the points which had seminorm zero now *are* zero, the new space is a normed space. Referring to the same example as before, this is how the $L^p$ spaces are constructed.
Comment: I unfortunately can't say much more than that without more context.
Comment: It may be that they are mentioned not because they are better but because the arise naturally.  One might find a seminorm and then declare $v_1$ and $v_2$ equivalent if the seminorm of $v_1-v_2$ is $0$, and then work with a quotient space that has a norm.
Answer: A common use is in topologizing certain function spaces. For example, let $\Omega \subset \mathbb{R}$ be open. We want a topology on $C^\infty(\Omega)$ the collection of smooth functions. Intuitively we'd like convergence $f_n \to f$ to imply the convergence locally of all derivatives. So what we do is we use a family of semi-norms to do it. $\|f\|_{K,n}$ is the sup norm of $f^{(n)}$ over the compact set $K$. There's no sensible reason to "quotient" by polynomials, so we have to admit the possibility that a non-zero function have non-zero $n^{th}$ derivative. (also a smooth function can be zero on some compact subset without being zero).
This becomes important in defining distribution spaces for PDE's
Comment: This is related to locally convex topological vector spaces: a TVS is LC if and only if its topology is generated by a family of seminorms.
Comment: The same wouldn't be true in the general case where you put some semi-norm on the partials in higher dimensions, but over $\mathbb{R}$, anything that has $n^th$ derivative zero on some $K$ will be a polynomial of degree at most $n$ on connected components of $K$. But why would we want to quotient by things that look like polynomials locally?
Comment: Good to know. But is there a possible way to find these non-zero functions with zero semi-norms so that we can factor out and have a norm on some quotient space?
Comment: so there is no way to go global?
Comment: We want the semi-norms to all be defined, but we often are working on open subsets where if we just took the sup norm of the nth over the whole thing it might be undefined for some functions. And from the distribution space view we want some way to talk about $C^\infty$ as a whole topologically, because it pairs off by integration with $C_0^\infty$ which gives an inclusion of smooth functions into distributions.

Why is semi-norm special and preferred?


How to access Ubuntu desktop from a Windows system?

Question: When using Terminal Server Client, it is possible to access the Windows desktop (remote desktop), from an Ubuntu PC.
Is the reverse possible?
What is the Windows XP application used to connect to an Ubuntu desktop?
Is the default mstsc application sufficient? If yes, what are the required settings on Ubuntu and Windows?
I want to view the desktop, not just an SSH terminal access.
Comment: Another option is X2go. Tutorial available [here](http://askubuntu.com/a/825313/594621)
Answer: Yes, it is possible. You can use Teamviewer or VNC to do just that in a Windows system.
Comment: Teamviewer is pure awesomeness!!! +1 for Teamviewer!
Answer: I used Remote Desktop to connect to my Ubuntu box. xrdp on the Ubuntu box is an adequate rdp server.
Tips here on getting it working if you're having problems with nothing displaying (except the background).
Answer: you can try tightVNC . And it's a simple guide to use tightVNC. Hope this helps
Comment: +1, it did worked for me...But it's not as clean as rdp
Answer: If you have XP Professional, one can also use Remmina remote Desktop Client on the Ubuntu side and just straight RDP to get to the XP machine. Simple VNC viewer will work in reverse. I always liked UltraVNC on the XP side.