Q:

spyne many-to-many version of server_sqlalchemy

I modified the server_sqlalchemy example to enable multi table as follows permissions = Array(Permission).store_as(table(multi=True)) and added methods get_permission, put_permission and get_all_permission similar to get_user, put_user and get_all_user.
On the client side I am using suds client as follows:
from suds.client import Client
c = Client('http://localhost:8000/?wsdl')

#create two permissions
p = c.factory.create('Permission')
p.application = 'usermgr'
p.operation = 'modify'
p.id = c.service.put_permission(p)

q = c.factory.create('Permission')
q.application = 'accountmgr'
q.operation = 'read'
q.id = c.service.put_permission(q)

#create two users
u = c.factory.create('User')
u.user_name = 'abcd'
u.full_name = 'abcd xyz'
u.email = 'abcd@xyz.com'
u.permissions = c.factory.create('PermissionArray')
u.permissions.Permission = [p,q]
u.id = c.service.put_user(u)

v = c.factory.create('User')
v.user_name = 'dcba'
v.full_name = 'dcba zyx'
v.email = 'dcba@zyx.com'
v.permissions = c.factory.create('PermissionArray')
v.permissions.Permission = [p,q] #note the same p,q used in u
v.id = c.service.put_user(v)

The put_user(v) fails due to

sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: permission.id [SQL: 'INSERT INTO permission (id, operation, application) VALUES (?, ?, ?)'] [parameters: ((3, 'modify', 'usermgr'), (4, 'read', 'accountmgr'))]

Clearly the code is trying to insert p,q gain into permission table and fails. Shouldn't multi table only insert into user_permissions table? If not, how to I achieve the desired behavior as shown in the client?
Thanks

A:

TL;DR: Use the first suggested workaround at the bottom of this post.

OK, I knew this'd be an issue.
Here's what's happening here:

You insert two permission objects successfully, get their server-generated ids.
You create a user object and put your newly inserted permissions inside the permissions array of the User instance.
As the put_user comes in as a separate request that uses a fresh session, sqlalchemy does not remember that these two permission objects are already in the database and tries to insert them again.
As the primary keys for these permissions already exist, you get that error.

So it's got nothing to do with having multi=True in the permissions array.
Relations in SQLAlchemy are "owner" relations by default. Here you need a "user" relation.
i.e. In this case, the User instances do not "own" permissions, they just "use" them. For example none of the permissions need to be deleted when a user is deleted.
I don't know of any way of defining a "user" relationship with SQLAlchemy. You need to bring the "used" objects into the session, and the only way of doing that is selecting them -- which is inefficient. Here's an answer by the author of SQLAlchemy about this subject: https://stackoverflow.com/a/9674552/1520211
As of 2.12, Spyne does not support marking relations as "owner/user" relations yet -- I just did not have time to study SQLAlchemy internals enough to come up with an elegant implementation.

So I got two workarounds for you:

user.permissions = [session.query(Permission).filter_by(id=perm.id).one()
                                             for perm in user.permissions]
VERY inefficient, but a single-line. Runs a select for every single incoming permission object. Because it uses .one() it will make sure clients can only add already-existing permissions. Note that Spyne will handle the NotFoundException gracefully and return a client error.
The efficient version that inserts the relationship rows manually.
permissions = user.permissions
user.permissions = []
session.add(user)
session.flush()
for perm in permissions:
    session.connection().execute("insert into user_permission "
                     "(user_id, permission_id) values (%s, %s)",
                                               perm.id, user.id)

Note that
i. This can be further optimized to use issue a single insert with multiple rows.
ii. If the permission id's are not valid, this will throw a foreign key error that Spyne knows nothing about. This means the client will receive a server error and think there's an issue on your side whereas the error is actually his fault. So if you care about retuning correct exceptions, you need to catch the database exception, make sure it's a constraint validation for the particular foreign key that points to the permissions table and raise a client error that says something along the lines of "Unknown permission id".

You can join http://lists.spyne.io/listinfo/people for further discussion if you prefer.


Q:

Verifying Lightweight Core Data Migration

I'm running a Core Data migration that adds a single inverse relationship to get rid of a warning I had.
After running the migration, how can I verify that the models I'm now using are referring to a specific xcdatamodel version (the latest one)?

A:

Lightweight migrations always target the latest model. If the migration succeeds, then the model you're using is the one marked as "current" in Xcode. In nearly every case, this is all you need.
If you want further confirmation:
In Xcode, you can add an identifier string to the data model, which can be different for each version of the model. You do this by selecting a version the data model in the file browser and opening the file inspector on the right side of the Xcode window. You'll see a section labeled "Identifier":

Enter any string that makes sense to you. At run time you can look up the value of this string using something like
let modelIdentifiers = context.persistentStoreCoordinator?.managedObjectModel.versionIdentifiers

This returns a set, because a model can be created by merging multiple model files. It will contain the string you entered above.
But this is almost never necessary. You can rely on the fact that the migration is using whichever model is marked as current in Xcode.


Q:

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar

My Android Manifiest
uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17"

values-v11:

values-v14:

<!--
    Base application theme for API 14+. This theme completely replaces
    AppBaseTheme from BOTH res/values/styles.xml and
    res/values-v11/styles.xml on API 14+ devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- API 14 theme customizations can go here. -->
</style>

The problem is I'm getting an error on bith values-v14(Styles.xml) and
values-v11(styles.xml) I am new in android. Thanx in advance

A:

Your current minSdkVersion is 8. Either change it to 14+ or use AppCompat support library. This library will let you draw action in lower APIs also.
Inside style tag you will have to use Theme.AppCompat.light as parent.


Q:

MFC: why it cannot pick up the right function based on argument type?

In the program, I try to bring up a dialog when a menu item is clicked.
void CMyDoc::OnFileTest()
{
    m_dialog = new CMyDialog;
    m_dialog->Create(CMyDialog::IDD, GetDesktopWindow());
    m_dialog->ShowWindow(SW_SHOW);
}

When I hover on "Create" function (VS-2008 IDE), it shows two overloads.
Create(LPCTSTR..., CWnd *);
Create(UINT..., CWnd *);

But when I build it, why the compiler insists it should take the first one. How to fix it?
error C2664: 'BOOL CDialog::Create(LPCTSTR,CWnd *)' : cannot convert parameter 1 from '' to 'LPCTSTR'

Edit
I try as suggested in the answer to cast IDD to UINT, but it doesn't work...
error C2664: 'BOOL CDialog::Create(LPCTSTR,CWnd *)' : cannot convert parameter 1 from 'UINT' to 'LPCTSTR'

In fact, I copy the code from this project: https://www.codeproject.com/Articles/1651/Tutorial-Modeless-Dialogs-with-MFC, which can compile without cast.
One difference is that I use Create in Doc, while the above uses in Dialog ??

A:

Have a look at the header for your dialog and you will see, as an example:
// Dialog Data
enum { IDD = IDD_DIALOG_ASSIGN_HISTORY };

Or you can hover the mouse over the IDD to see the definition:

Notice that the variable IDD is actually an enum? Specifically it is not of type UINT. As a result your compiler can't find the right override and ends up trying the LPCTSTR version, and fails.
As already answered, you need to cast your IDD variable,
m_dialog->Create(static_cast<UINT>(CMyDialog::IDD), GetDesktopWindow());

This way the compiler will not complain.

The Win32 SDK GetDesktopWindow returns a HWND and not CWnd *. So you are back to the same scenario. You could casting to CWnd * or using this if that is acceptable.
From my research you should be able to do this to get a CWnd *:
CWnd* pWnd = CWnd::FromHandlePermanent ( GetDesktopWindow());

I have been informed in the comments that there is a simpler solution:
m_dialog->Create(static_cast<UINT>(CMyDialog::IDD), CWnd::GetDesktopWindow());

See CWnd::GetDesktopWindow() for more info.


Q:

foreign key editing

why is it the first time i edit a forein key it allows me to edit its value and then after the second try it brings up an error like this
Cannot add or update a child row: a foreign key constraint fails (`sadsystem/products`, CONSTRAINT `products_ibfk_3` FOREIGN KEY (`size_id`) REFERENCES `product_sizes` (`size_id`) ON DELETE CASCADE ON UPDATE CASCADE)

you can see my edit query
if($mode=="editproduct")
{
$product_id=$_GET["product_id"];
$sql="SELECT * FROM products WHERE product_id='$product_id'";
$result=mysql_query($sql,$connection) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
$product_id=$row['product_id'];
$product_name=$row['product_name'];
$product_color=$row['product_color'];
$size_id=$row['size_id'];
$product_description=$row['product_description'];
$brand_id=$row['brand_id'];
$category_id=$row['category_id'];
$supplier_id=$row['supplier_id'];
$product_standardPrice=$row['product_standardPrice'];
$product_unitPrice=$row['product_unitPrice'];
} ?>
<link href="default.css" rel="stylesheet" type="text/css">
<form method="post" action="forms.php">

Edit Product
<input type="hidden" name="product_id" value="<? echo $product_id ;?>" />

Product Name
<input type="text" name="product_name" value="<? echo $product_name ;?>" />

Color
<input type="text" name="product_color" value="<? echo $product_color ;?>" />

Size

<?
    $query="SELECT * FROM product_sizes ORDER BY size_id ASC";
    $result = mysql_query ($query);
    echo "<select name=size_id>";
    while($nt=mysql_fetch_array($result))
    {
    echo "<option value=$nt[$size_id]>$nt[size_name]</option>";
    }
    echo "</select>";
?>

Description
<input type="text" name="product_description" value="<? echo $product_description ;?>" />

Brand

<?
    $query="SELECT * FROM brands ORDER BY brand_name ASC";
    $result = mysql_query ($query);
    echo "<select name=brand_id>";
    while($nt=mysql_fetch_array($result))
    {
    echo "<option value=$nt[brand_id]>$nt[brand_name]</option>";
    }
    echo "</select>";
?>

Category

<?
    $query="SELECT * FROM categories ORDER BY category_name ASC";
    $result = mysql_query ($query);
    echo "<select name=category_id>";
    while($nt=mysql_fetch_array($result))
    {
    echo "<option value=$nt[category_id]>$nt[category_name]</option>";
    }
    echo "</select>";
?>

Supplier

<?
    $query="SELECT * FROM suppliers ORDER BY supplier_name ASC";
    $result = mysql_query ($query);
    echo "<select name=supplier_id>";
    while($nt=mysql_fetch_array($result))
    {
    echo "<option value=$nt[supplier_id]>$nt[supplier_name]</option>";
    }
    echo "</select>";
?>

Standard Price
<input type="text" name="product_standardPrice" value="<? echo $product_standardPrice ;?>"/>

Unit Price
<input type="text" name="product_unitPrice" value="<? echo $product_unitPrice ;?>" />

<input type="submit" name="editproduct" value="Save" />

</form>
<? }

A:

Cannot add or update a child row: a foreign key constraint fails (`sadsystem/products`, CONSTRAINT `products_ibfk_3` FOREIGN KEY (`size_id`) REFERENCES `product_sizes` (`size_id`) ON DELETE CASCADE ON UPDATE CASCADE)

This message is telling you that you cannot perform the operation you are trying to perform because, it is in violation of the foreign key constraint.
You need to evaluate your query to verify that you are not:
(a) adding a new value to the foreign key table prior to using it in sadsystem/products ( which also refers to performing an insert, update, or delete).
(b) trying to delete a value from the foreign key table while it is linked to another table that relies on the value.
(c) some other obscure issue.


Q:

Computer not POSTing "randomly"?

I have a custom built PC that is exhibiting some...odd... behavior, something I've never seen before. It was working fine one day, and the next day, it wouldn't start. Seeing as I wanted an upgrade anyway, I purchased a new motherboard that was compatible with all my parts. While replacing the motherboard, I accidentally damaged the CPU. Well, I wanted a new one anyway... so I got a new one. Seeing as I was replacing a ton of parts already, I bought a new PSU because the old one was super loud. When I slapped it all together, it starts up, lights, fans, drives, they all start. But I get no display from the monitor. No beeps, which I believe means it doesn't POST. I figured it was the RAM, because after removing the sound card and graphics card, there was nothing else that I hadn't replaced. When I remove both sticks of RAM, I get a continuous beeping, and according to the mobo handbook, means no RAM. So I think the mobo is functional, or atleast partly. I bought new RAM, but it still didn't work. I tried 3 monitors, with both VGA and DIV. So it's probably not the monitor, either.
Now, let me get to the random part. Every 20 or so boots (I should also mention, for about 3 out of 5 boots I have to unplug the PC because it won't powerdown via the button), it will POST and I'll get display. Then, after about 2 or 3 resets, it won't work again. This confuses me so much, because even when I change nothing, it will/will not work. My thought is that maybe it has something to do with the RAM not clearing or something. I also reset the CMOS battery, incase that had anything to do with it, but no eval. I found some weird suggestion online about holding the power button for 30 seconds while it was unplugged. That did nothing, but I didn't expect it would...
I've replaced just about the entire computer, and all the parts are compatible. Done about everything I can think of, but nothing has worked. Hopefully someone can help me here.

And as I side note: When I do get my computer to boot, it says my hardware has changed and I have to re-activate windows. But it says I have to call Microsoft to do it. So I get this fancy automated voice that asks me to enter in a code into windows, then it asks me "How many computers have you activated with this copy of Windows?". Well, I had it on my computer before I replaced everything, so I said 1. Then he yelled at me for violating my 1-use license. I dunno what's going on there, do I have to re-purchase Windows 7? And they wonder why people pirate software... That's just a bonus question, though.
Specs:

8GB of DDR2 RAM (Corsair)
AMD CPU (I don't know what GHz or model because I can't find the box... (I think its 4 cores of 2.8Ghz)
ASRock A785GM-LE Motherboard

A:

Clear the CMOS settings. What's happening is that you have some setting that's preventing the system from POSTing. When the motherboard detects a few failed POSTs, it tries POSTing with default settings, which then works.
Most likely, you customized some settings for your old RAM and forgot to remove them before you switched to the new RAM.

A:

While replacing the motherboard, I accidentally damaged the CPU.

How, exactly?  I ask, because is it possible you damaged the motherboard?  As in... damaged a capacitor?  Because the behavior you are describing sounds like a power issue, and not necessarily a PSU issue... which could and would indicate a potential capacitor issue.  I've known more than one motherboard to operate with blown capacitors... just not reliably.  I'm not saying that you blew one... but if it was damaged... that could explain things.
Clearing the CMOS wouldn't make Windows require activation.  Changing a sound card wouldn't do it either.  Even changing a sound card and video card at the same time.  Changing a motherboard can trigger that "different hardware" dealio (although not necessarily... I've managed it more than once with the right mobo swap).  So, if this message is the one you get after you replaced the motherboard, that's most likely why you got it.
So... power.  Either PSU, or more likely a damaged capacitor or two... or three, etc.


Q:

Merge table by aggregating a 3 year average from second df

I am modelling the effects of a variety of variables on the growth of fish within a particular haul. I want to calculate a three year average catch rate for each haul based on its geographical grid location. I need a formula to take the 'Stat_sq' (geographic grid square) and the 'Year' of the fishing trip (contained in the first data frame) and generate an average catch rate for the three preivous years by aggregating the mean catch rates by 'Stat_sq' and 'Year' from the second data frame.
The year range is 93,94,95,96,97,98,99,00,01,02,03,04,05,06,07,08,09,10,11,12,13,14
I would also like it to just return a two year average or just a single year value if there is NA/missing values.
Dataframe1
Trip_Id Stat_sq Year
0113A_1   48E8  13
0113A_10  49E8  13
0113A_11  49E8  12
0113A_12  49E8  13
0113A_13  49E8  12
0113A_15  49E8  11
0113A_16  49E8  10
0113A_18  50E8  13
0113A_19  50E8  12

Dataframe2
Stat_sq Year    Catch_Rate
48E8    13      12.353719
48E8    12      16.508482
48E8    11      2.841493
42E8    10      12.721584
50E8    13      12.419484
50E9    12      22.461538
50E8    11      28.141433
44E7    00      29.681110
44E8    00      5.427430
45E6    00      13.259770
45E7    00      18.250903
45E8    00      62.222222

For exmaple for haul 0113A_1 i would like the average catch rate in square 48E8 for years 13,12,11 (3 years including the current year) = 10.567898
Any help appreciated.

A:

May be this helps
 df1$Yr <- with(df1, as.numeric(ifelse(as.numeric(Year)>=93,
                              paste0(19,Year), paste0(20,Year))))

 df2$Yr <-  with(df2, as.numeric(ifelse(as.numeric(Year)>=93,
                              paste0(19,Year), paste0(20,Year))))

 res <-   unsplit(lapply(split(df1, df1$Stat_sq),
            function(x) {
           x1 <- df2[df2$Stat_sq %in% unique(x$Stat_sq),]
             x$Avg <- sapply(seq_len(nrow(x)), function(i) {
                   x2 <- x[i,]
                   indx <- x1$Yr %in% seq(x2$Yr-2, x2$Yr)
                   if(length(indx)>0) mean(x1$Catch_Rate[indx], na.rm=TRUE)
                    else NA})
              x}),
            df1$Stat_sq)

 head(res[,-4],2)
 #   Trip_Id Stat_sq Year     Avg
 #1  0113A_1    48E8   13 10.5679
 #2 0113A_10    49E8   13      NA

data
 df1 <- structure(list(Trip_Id = c("0113A_1", "0113A_10", "0113A_11",
 "0113A_12", "0113A_13", "0113A_15", "0113A_16", "0113A_18", "0113A_19"
 ), Stat_sq = c("48E8", "49E8", "49E8", "49E8", "49E8", "49E8",
 "49E8", "50E8", "50E8"), Year = c("13", "13", "12", "13", "12",
 "11", "10", "13", "12")), .Names = c("Trip_Id", "Stat_sq", "Year"
 ), class = "data.frame", row.names = c(NA, -9L))

 df2 <- structure(list(Stat_sq = c("48E8", "48E8", "48E8", "42E8", "50E8",
 "50E9", "50E8", "44E7", "44E8", "45E6", "45E7", "45E8"), Year = c("13",
 "12", "11", "10", "13", "12", "11", "00", "00", "00", "00", "00"
 ), Catch_Rate = c(12.353719, 16.508482, 2.841493, 12.721584,
 12.419484, 22.461538, 28.141433, 29.68111, 5.42743, 13.25977,
 18.250903, 62.222222)), .Names = c("Stat_sq", "Year", "Catch_Rate"
 ), class = "data.frame", row.names = c(NA, -12L))


Q:

How to mandate a certain text phase in a textfield in swift

How do I make sure my email field has text ending with @companyname.com
so it wont proceed if it ends with something like @gmail.com?
@IBAction func login(_ sender: Any) {
    if self.emailField.text != "" || self.passwordField.text != "" && self.emailField.text == //what do i put here?//
    {
    }
}

A:

One option would be to use hasSuffix(:) to check for a particular suffix.
@IBAction func login(_ sender: Any) {
    if self.emailField.text != "" || self.passwordField.text != "" && self.emailField.text.hasSuffix("@companyname.com")
    {
    }
}


Q:

Kendo UI masked textbox - unable to change default prompt char

I am trying to change the default promptChar for a Kendo MaskedTextBox. I tried with code:

Enter a number

        <input data-role="maskedtextbox"
               data-mask="(999) 000-0000"
               data-promptChar="#"
               data-bind="visible: isVisible,
                          enabled: isEnabled,
                          value: phoneNumber,
                          events: { change: onChange }"
               style="width: 200px">

However, the textbox still has '_' as the prompt character. Any idea why this is happening? How do I fix this?
Thanks in advance.

A:

Change data-promptChar="#" to data-prompt-char="#"
See working sample http://jsbin.com/xivede/1/edit?html,js,output


Q:

Getting Session error on live site

I have started my session in config.php file & i have included that file on every page on my site,
my site works fine in localhost,
but when i have done live to it,it shows error like this,
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent

Any suggestions...
Thanks,

A:

check that you don't send content before calling session_start. Just make session_start the first thing you do in your PHP file.
<?php session_start(); ?>


Q:

Determine if a jQuery event has expired (event bubbling has ended)

DOM events have three phases: capture, target, and bubble, and the eventPhase property of a DOM event reflects which phase the event is in.
jQuery events also have this property, but it doesn't seem to update as the event moves through its life-cycle. I think it's just be a snapshot of a DOM event at a particular time.
Is there a way to determine from a jQuery event if the original event's life-cycle has ended without inspecting the original event? (Inspecting the original event won't work for me since IE6-8 events don't have properties like eventPhase or currentTarget that can be used to determine if an event is still bubbling.)

A:

As you mentioned its not supported in older versions of IE therefore jQuery will not help you for those cases anyways. So for now just use eventPhase on the original DOM event when it is available.


Q:

Invariant error in react native cannot find store

i have been setting up redux for a react native application i have been working on for a few days. I keep getting invariant error could not find store in either the context or props. I have been googling it for days and tried multiple different solutions, but I cant seem to be able to fix this error.
Store:
`import React from 'react';
import { render } from 'react-dom'
import { Provider } from 'react-redux';
import { createStore,applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import combineReducers from "./reducers/combineReducers";
import App from './App'

const store = createStore(combineReducers ,applyMiddleware(thunk));

render(
    <Provider store={store}>
        <App/>
    </Provider>,
    document.getElementById('App')
);`

The App component
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
import MainMenu from "./Components/MainMenu";
import {Root} from "native-base";
import {connect} from 'react-redux';
import {Font, AppLoading} from 'expo';

export class App extends Component {
    state = {
        loadingFont: true,
        testText:'Test'
    };

        async componentDidMount() {
            try {
                await Font.loadAsync({
                    'pixel-font': require('./assets/fonts/Roboto-Medium.ttf'),
                });
                this.setState({loadingFont: false});

            }catch (e) {
                console.log(e)
            }
        }

    render() {
        if (this.state.loadingFont) {
            return (
                <Root>
                    <AppLoading/>
                </Root>
            );
        }
        return (
            <View style={styles.container}>
                <MainMenu/>
            </View>
        );
    }
}
const mapStateToProps = state => {
    return {productions:state.productions}
};

export default connect(mapStateToProps)(App);

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#fff',
        justifyContent: 'center',
    },
});

I know this is a question that has been asked quite a few times, but i feel Like I have browsed through all of the answers and found none that work. At this point I know that i have made an error somewhere, but after looking at this for a couple of days i have sort of gone blind to finding any solution on my own.

A:

Export the store from your store file and import it to your App.js file. The Provider should also be in your App.js file wrapped around <Root>. Are you working in react-native? If so, you wouldn't use React-Dom, Expo will load the App.js file.


Q:

MRJob sort reducer output

Is there any way to sort the output of reducer function using mrjob?
I think that the input to reducer function is sorted by the key and I tried to exploit this feature to sort the output using another reducer like below where I know values have numeric values, I want to count number of each key and sort keys according to this count:
def mapper_1(self, key, line):
    key = #extract key from the line
    yield (key, 1)

def reducer_1(self, key, values):
    yield key, sum(values)

def mapper_2(self, key, count):
    yield ('%020d' % int(count), key)

def reducer_2(self, count, keys):
    for key in keys:
        yield key, int(count)

but it's output is not correctly sorted! I suspected that this weird behavior is due to manipulating ints as string and tried to format it as this link says but It didn't worked!
IMPORTANT NOTE: When I use the debugger to see the order of output of reducer_2 the order is correct but what is printed as output is something else!!!
IMPORTANT NOTE 2: On another computer the same program on the same data returns output sorted as expected!

A:

You can sort the values as integers in second reducer and then converting them in to the zero padded representation:
import re

from mrjob.job import MRJob
from mrjob.step import MRStep

WORD_RE = re.compile(r"[\w']+")

class MRWordFrequencyCount(MRJob):

    def steps(self):
        return [
            MRStep(
                mapper=self.mapper_extract_words, combiner=self.combine_word_counts,
                reducer=self.reducer_sum_word_counts
            ),
            MRStep(
                reducer=self.reduce_sort_counts
            )
        ]

    def mapper_extract_words(self, _, line):
        for word in WORD_RE.findall(line):
            yield word.lower(), 1

    def combine_word_counts(self, word, counts):
        yield word, sum(counts)

    def reducer_sum_word_counts(self, key, values):
        yield None, (sum(values), key)

    def reduce_sort_counts(self, _, word_counts):
        for count, key in sorted(word_counts, reverse=True):
            yield ('%020d' % int(count), key)

Well this is sorting the output in memory, which migtht be a problem depending on the size of the input. But you want it sorted so it has to be sorted somehow.


Q:

Help understanding unipolar transfer function

There is a question I am stuck on using the following formula for the unipolar transfer function:
f(net)=     1
         __________
               -net
         1 + e

The example has the following:
out =        1
        ____________  = 0.977
               -3.75
        1 + e

How do we arrive at 0.977?
What is e?

A:

e = 2.71828... is the base of natural logarithms. It's a mathematical constant that comes up in many different equations, similar to π. You will see it all the time when doing exponents and logarithms.
Plug it into your equation and you get 0.977.

A:

While factually correct the other responses merely provide the value of e and confirm the underlying computation.  This type of sigmoid functions is so ubiquitous to neural networks that some additional insight may be welcome.
Essentially the exponential function (e to the x power),  has a very characteristic curve:

Mostly flat at zero (very slightly above zero, actually),  from - infinity to about  -2
incrementally sharp turn towards the vertical, between about -2 and +4
quasi "vertical", with values in excess of 150 and increasingly huge, from +5 to infinity

As a result exponential curves are very useful for producing "S-shaped" functions; BTW, "S" is Sigma in Greek which supplied the etymology for "sigmoid". Such functions are often patterned on the formula shown in the question:
 1/(1 + e^-x)

where x is the variable.  Typically such functions also include constants aimed at stretching the range (the input zone where changes in x are significant) and/or at modifying the curve in this middle zone.
The result of such functions is that up to a particular value of the input, the function is quasi constant, then, for a particular range of inputs, the function provides a increasing output, and finally past the upper value of the range, the function is quasi constant.  Also looking in more details, such Sigmoids have a point of inflection which correspond to a reversing of the rate of change of the ouptut and which also marks an area of the curve, on either side, where the changes are the slowest, relatively.
In turn, such S-shaped curves (1) are very useful to normalize the output of neural network neurons, or more generally, to normalize various numeric values during processes of various nature.  Intuitively these correspond to a "sweet spot" or a "sweet range" of the underlying neuron or device.
(1) Or also, possibly,  "step-down" shaped curves, i.e. curves with a mostly constant high value, a decreasing value within the mid-range, and a low mostly constant value thereafter.


Q:

List Comparison in Python with Diff as output

The below script i have to compare Test1 vs Test2.Test1 and Test2 data is mentioned in the bottom .I tried to make it a generic one so that it will work for different devices also.The below script i have to compare Test1 vs Test2.Test1 and Test2 data is mentioned in the bottom .I tried to make it a generic one so that it will work for different devices also
import re
    data_cleaned = {}
    current_key = ''
    action_flag = False
    data_group = []
    if_found_vlan = True

    output = open('./output.txt','r').read()

    switch_red = re.findall(r'(\w*-RED\d{0,1})', output)[0]
    switch_blue = re.findall(r'(\w*-BLUE\d{0,1})', output)[0]

    for line in open('./output.txt'):
        m = re.match(r'(\w*-RED\d{0,1}|\w*-BLUE\d{0,1})# sh run vlan \d+', line)

        if m:
            if not if_found_vlan:
                data_cleaned[current_key].append([])
            if_found_vlan = False

            current_key = m.group(1)
            if not data_cleaned.has_key(current_key):
                data_cleaned[current_key] = []
            continue

        mm = re.match(r'vlan \d+', line)
        if mm:
            if_found_vlan = True
            action_flag = True
            data_group = []
        if action_flag and '' == line.strip():
            action_flag = False
            data_cleaned[current_key].append(data_group)

        if action_flag:
            data_group.append(line.replace('\r', '').replace('\n', ''))

    if not if_found_vlan:
        data_cleaned[current_key].append([])
    #print ("+++++++++++++++++ The missing configuration ++++++++++++++\n")
    print switch_blue + "#" + " has below missing VLAN config\n "
    p = [item for index, item in enumerate(data_cleaned[switch_blue]) if [] != [it for it in item if it not in data_cleaned[switch_red][index]]]
    print('\n'.join(['\n'.join(item) for item in p]))
    print ("+++++++++++++++++++++++++++++++\n")
    print switch_red + "#" + " has below missing VLAN config\n "
    q = [item for index, item in enumerate(data_cleaned[switch_red]) if [] != [it for it in item if it not in data_cleaned[switch_blue][index]]]
    print('\n'.join(['\n'.join(item) for item in q]))

A:

Update with your raw output, I think use a one-dimensional list to represent your output is not a good way for further handling.
When we handle a data, we first need to clean the data & setup a model easy to handle for further program processing, so I use a dict with a two-dimensional list inside it to model your output, and finally easier to process.
import re

data_cleaned = {}
current_key = ''
action_flag = False
data_group = []
if_found_vlan = True

for line in open('./output.txt'):
    m = re.match(r'(Test\d+)# sh run vlan \d+', line)
    if m:
        if not if_found_vlan:
            data_cleaned[current_key].append([])
        if_found_vlan = False

        current_key = m.group(1)
        if not data_cleaned.has_key(current_key):
            data_cleaned[current_key] = []
        continue

    mm = re.match(r'vlan \d+', line)
    if mm:
        if_found_vlan = True
        action_flag = True
        data_group = []
    if action_flag and '' == line.strip():
        action_flag = False
        data_cleaned[current_key].append(data_group)

    if action_flag:
        data_group.append(line.replace('\r', '').replace('\n', ''))

if not if_found_vlan:
    data_cleaned[current_key].append([])

print ("+++++++++++++++++ The missing configuration is++++++++++++++\n")
p = [item for index, item in enumerate(data_cleaned['Test2']) if [] != [it for it in item if it not in data_cleaned['Test1'][index]]]
print('\n'.join(['\n'.join(item) for item in p]))
print ("+++++++++++++++++ The missing configuration is++++++++++++++\n")
q = [item for index, item in enumerate(data_cleaned['Test1']) if [] != [it for it in item if it not in data_cleaned['Test2'][index]]]
print('\n'.join(['\n'.join(item) for item in q]))


Q:

How can I write a C function that takes either an int or a float?

I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want f(5) and f(5.5) to be acceptable inputs.
I don't think I can use if (!PyArg_ParseTuple(args, "i", $value)) because it only takes only int or only float.
How can I make my function allow inputs that are either ints or floats?
I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?

A:

If you declare a C function to accept floats, the compiler won't complain if you hand it an int. For instance, this program produces the answer 2.000000:
#include <stdio.h>

float f(float x) {
  return x+1;
}

int main() {
  int i=1;
  printf ("%f", f(i));
}

A python module version, iorf.c:
#include <Python.h>

static PyObject *IorFError;

float f(float x) {
  return x+1;
}

static PyObject *
fwrap(PyObject *self, PyObject *args) {
  float in=0.0;
  if (!PyArg_ParseTuple(args, "f", &in))
    return NULL;
  return Py_BuildValue("f", f(in));
}

static PyMethodDef IorFMethods[] = {
    {"fup",  fwrap, METH_VARARGS,
     "Arg + 1"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC
initiorf(void)
{
  PyObject *m;

  m = Py_InitModule("iorf", IorFMethods);
  if (m == NULL)
    return;

  IorFError = PyErr_NewException("iorf.error", NULL, NULL);
  Py_INCREF(IorFError);
  PyModule_AddObject(m, "error", IorFError);
}

The setup.py:
from distutils.core import setup, Extension

module1 = Extension('iorf',
                    sources = ['iorf.c'])

setup (name = 'iorf',
       version = '0.1',
       description = 'This is a test package',
       ext_modules = [module1])

An example:
03:21 $ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import iorf
>>> print iorf.fup(2)
3.0
>>> print iorf.fup(2.5)
3.5


Q:

Oracle integer to number conversion

According to the Oracle documentation, creating a table with a column of ANSI type INT, Oracle will convert it to NUMBER(38).  According to the same document, NUMBER(38) is supposed to be a NUMBER with a precision of 38 and a scale of 0. But in practice, I am seeing a NUMBER with data_precision set to NULL and a data_length set to 22.
SQL> create table ltheisen.silly ( id int );

Table created.

SQL> select substr(data_type,1,10), data_length, data_scale, data_precision from
 all_tab_columns where owner='LTHEISEN' and table_name='SILLY' and column_name='
ID';

SUBSTR(DATA_TYPE,1,10)                   DATA_LENGTH DATA_SCALE DATA_PRECISION
---------------------------------------- ----------- ---------- --------------
NUMBER                                            22          0

What gives?
Also, I am trying to do a generic conversion from Oracle to ANSI.  Is there any way to determine from the metadata that the NUMBER was created as, or fits into an INT?
Lastly, I tried creating with BINARY_INTEGER which appears in the documentation, but the create statement fails:
SQL> create table ltheisen.silly ( id binary_integer );
create table ltheisen.silly ( id binary_integer )
                                 *
ERROR at line 1:
ORA-00902: invalid datatype

What am I missing?
-------------------- UPDATE -----------------------------
Reading a little deeper gives this gem:

Specify a floating-point number using the following form:
NUMBER
The absence of precision and scale designators specifies the maximum range and precision
for an Oracle number.

So since the datatype is NUMBER and there is no precision specified, we can assume it is maximum precision?

A:

A DATA_LENGTH of 22 is just the largest number of bytes it can take to store the largest possible number (Oracle uses 2 digits per byte). A NULL DATA_PRECISION implies the maximum of 38.
You can verify this with DBMS_METADATA:
SQL>  create table sotmp ( a int );

Table created.

SQL> select dbms_metadata.get_ddl('TABLE','SOTMP')
  2  from dual;

DBMS_METADATA.GET_DDL('TABLE','SOTMP')
--------------------------------------------------------------------------------

  CREATE TABLE "PHIL"."SOTMP"
   (    "A" NUMBER(*,0)
   ) SEGMENT CREATION DEFER

SQL>

(The "*" in the above output denotes the maximum precision).
BINARY_INTEGER is not a data type that can be used in table columns. It can only be used as a PL/SQL variable datatype.


Q:

Mastermind check result python

At the moment I am trying to make a mastermind-type code, like the game.
I am currently stuck on the bit where I am trying to check if the users guess is correct.
colours = ["R","O","Y","G","B","I","V"]

n = 1
ans = random.choices(colours, k = 4)
print(*ans)
guess = input("what is your guess? ")

[guess[i:i+n] for i in range(0, len(guess), n)]

guess = (guess.upper())

def check():
    correct = False
    right = 0
    wrong = 0
    if guess == ans:
        correct = True
    elif guess != ans:
        correct = False
        for i in range(0,(len(guess))):
            for x in range(0,(len(ans))):
                if guess[i] in ans:
                    wrong += 1

                    break

    print(right,"black pegs")
    print(wrong,"white pegs")
    return
check()

If ans = "R O Y Y", and guess = "R G O O"
I would want the output to be
1 white pegs
1 black pegs

what it actually gives me is
3 white pegs
0 black pegs

white pegs means right colour, wrong place, black pegs means right colour, right place
How would I go around coding the black pegs?

A:

I think part of your problem is that you've not separated the logic into functions, that will make it easier to understand what needs done, so below I've separated the work into count_white, count_black and check.
The first thing you'll notice is that ["R","O","Y","Y"] and ["R","G","O","O"] gave 3 white pegs, that's because the R is being classed as white (although it should be black) and BOTH Os are being counted against the O in ans hence 3, the white pegs are in fact a whole lot harder to calculate than the black pegs.
The black pegs can be calculated using
black = 0
for i in range(len(guess)):
    if guess[i] == ans[i]:
        black += 1

or, more pythonic and in a function:
def count_black(ans, guess):
    return sum([ans[i] == guess[i] for i in range(len(ans))])

For the whites, you just need to check if a colour occurs in both lists, and if it does, remove it from ans so you don't check it more than once:
def count_white(ans, guess):
    temp_ans = ans[:]
    white = 0
    for i in guess:
        if i in temp_ans:
            temp_ans.remove(i)
            white += 1
    return white

Note that the above ignores if a peg is in the right position, that's okay, because we know how many are in the right position from the black count.
Now that these have been moved into functions your check can simply be:
def check(ans, guess):
    white = count_white(ans, guess)
    black = count_black(ans, guess)
    white -= black

    print(black,"black pegs")
    print(white,"white pegs")

    return black == 4

Resulting in:
>>> check(["R","O","Y","Y"],["R","G","O","O"])
1 black pegs
1 white pegs
False

Note that the returned False is whether or not it was correct.
Thus all your code can be written as:
import random
colours = ["R","O","Y","G","B","I","V"]
ans = [random.choice(colours) for i in range(4)]
print(''.join(ans))

def count_white(ans, guess):
    temp_ans = ans[:]
    pegs = 0
    for i in guess:
        if i in temp_ans:
            temp_ans.remove(i)
            pegs += 1
    return pegs

def count_black(ans, guess):
    return sum([ans[i] == guess[i] for i in range(len(ans))])

def check(ans, guess):
    white = count_white(ans, guess)
    black = count_black(ans, guess)
    white -= black

    print(black,"black pegs")
    print(white,"white pegs")

    return black == 4

guess = []
while guess != ans:
    guess = list(input("what is your guess?").upper())
    check(ans, guess)


Q:

How to compare VALUE of two strings?

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
I am now in a middle of a question that asks me to compare between two strings(input from the user) and check if the two contain the same letters.
example:
areAnagrams("asd","dsa") -> true
areAnagrams("Debit Card","Bad Credit")=> true

got the idea?
I know that the == check only if them both are refering to the same object.
I thought that
public int compareTo(String otherString)

should have done the job.
but it doesnt work =\
what i did till now is:
public static boolean areAnagrams(String a, String b)
{
int x=0;
    a.trim();
    b.trim();

    x=a.compareTo(b);
    System.out.println(x);
    return x==0 ? true:false;

}
    public static void main(String[] args)
    {
Scanner temp= new Scanner(System.in);
Scanner temp2= new Scanner(System.in);
String a= temp.next();
String b= temp2.next();
System.out.println(areAnagrams(a,b));

    }

}

but it doesnt work. i think there is a command that should compare value's but i couldnt find it online.
will apriciate your help
thanks!

A:

How about trying with Arrays like this:-
 char[] w1= firstWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
 char[] w2= secondWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
 Arrays.sort(w1);
 Arrays.sort(w2);
 return Arrays.equals(w1, w2);


Q:

C++ Cache performance odd behavior

I read an article (1.5 years old http://www.drdobbs.com/parallel/cache-friendly-code-solving-manycores-ne/240012736) which talks about cache performance and size of data.  They show the following code which they say they ran on an i7 (sandy bridge)
static volatile int array[Size];
static void test_function(void)
{
    for (int i = 0; i < Iterations; i++)
        for (int x = 0; x < Size; x++)
          array[x]++;
}

They make the claim that if they keep Size*Iterations constant, increasing Size,  when the size in memory of array increases beyond the L2 cache size they observe a huge spike in time taken to execute (10x).
As an exercise for myself I wanted to try this to see if I could reproduce their results for my machine . (i7 3770k, win7, visual c++ 2012 compiler, Win32 debug mode, no optimizations enabled).  To my surprise though, I am not able to see an increase in time taken to execute (even beyond the L3 cache size) which made me think the compiler was somehow optimizing this code. But I dont see any optimizations either.  The only change in speed i see is that below the word size of my machine it takes slightly longer.  Below are my timings, code listing, and pertinent disassembly.
Does anyone know why:
1) Why the time taken does not increase at all regardless of the size of my array?  Or how I could find out?
2) Why does the time taken start high and then decrease until the cache line size is reached, shouldn't more iterations be processed without reading from cache if the data is less than the line size?

Timings:
Size=1,Iterations=1073741824, Time=3829
Size=2,Iterations=536870912, Time=2625
Size=4,Iterations=268435456, Time=2563
Size=16,Iterations=67108864, Time=2906
Size=32,Iterations=33554432, Time=3469
Size=64,Iterations=16777216, Time=3250
Size=256,Iterations=4194304, Time=3140
Size=1024,Iterations=1048576, Time=3110
Size=2048,Iterations=524288, Time=3187
Size=4096,Iterations=262144, Time=3078
Size=8192,Iterations=131072, Time=3125
Size=16384,Iterations=65536, Time=3109
Size=32768,Iterations=32768, Time=3078
Size=65536,Iterations=16384, Time=3078
Size=262144,Iterations=4096, Time=3172
Size=524288,Iterations=2048, Time=3109
Size=1048576,Iterations=1024, Time=3094
Size=2097152,Iterations=512, Time=3313
Size=4194304,Iterations=256, Time=3391
Size=8388608,Iterations=128, Time=3312
Size=33554432,Iterations=32, Time=3109
Size=134217728,Iterations=8, Time=3515
Size=536870912,Iterations=2, Time=3532

code:
#include <string>
#include <cassert>
#include <windows.h>

template <unsigned int SIZE, unsigned int ITERATIONS>
static void test_body(volatile char* array)
{
     for (unsigned int i = 0; i < ITERATIONS; i++)
    {
        for (unsigned int  x = 0; x < SIZE; x++)
        {
            array[x]++;
        }
    }
}

template <unsigned int SIZE, unsigned int ITERATIONS>
static void test_function()
{
    assert(SIZE*ITERATIONS == 1024*1024*1024);
    static volatile char array[SIZE];

    test_body<SIZE, 1>(array); //warmup

    DWORD beginTime = GetTickCount();
    test_body<SIZE, ITERATIONS>(array);
    DWORD endTime= GetTickCount();
    printf("Size=%u,Iterations=%u, Time=%d\n", SIZE,ITERATIONS, endTime-beginTime);
}

int main()
{
    enum { eIterations= 1024*1024*1024};
    test_function<1, eIterations>();
    test_function<2, eIterations/2>();
    test_function<4, eIterations/4>();
    test_function<16, eIterations/16>();
    test_function<32, eIterations/ 32>();
    test_function<64, eIterations/ 64>();
    test_function<256, eIterations/ 256>();
    test_function<1024, eIterations/ 1024>();
    test_function<2048, eIterations/ 2048>();
    test_function<4096, eIterations/ 4096>();
    test_function<8192, eIterations/ 8192>();
    test_function<16384, eIterations/ 16384>();
    test_function<32768, eIterations/ 32768>();
    test_function<65536, eIterations/ 65536>();
    test_function<262144, eIterations/ 262144>();
    test_function<524288, eIterations/ 524288>();
    test_function<1048576, eIterations/ 1048576>();
    test_function<2097152, eIterations/ 2097152>();
    test_function<4194304, eIterations/ 4194304>();
    test_function<8388608, eIterations/ 8388608>();
    test_function<33554432, eIterations/ 33554432>();
    test_function<134217728, eIterations/ 134217728>();
    test_function<536870912, eIterations/ 536870912>();
}

Disassembly
    for (unsigned int i = 0; i < ITERATIONS; i++)
00281A59  mov         dword ptr [ebp-4],0
00281A60  jmp         test_body<536870912,2>+1Bh (0281A6Bh)
00281A62  mov         eax,dword ptr [ebp-4]
00281A65  add         eax,1
00281A68  mov         dword ptr [ebp-4],eax
00281A6B  cmp         dword ptr [ebp-4],2
00281A6F  jae         test_body<536870912,2>+53h (0281AA3h)
    {
        for (unsigned int  x = 0; x < SIZE; x++)
00281A71  mov         dword ptr [ebp-8],0
00281A78  jmp         test_body<536870912,2>+33h (0281A83h)
00281A7A  mov         eax,dword ptr [ebp-8]
    {
        for (unsigned int  x = 0; x < SIZE; x++)
00281A7D  add         eax,1
00281A80  mov         dword ptr [ebp-8],eax
00281A83  cmp         dword ptr [ebp-8],20000000h
00281A8A  jae         test_body<536870912,2>+51h (0281AA1h)
        {
            array[x]++;
00281A8C  mov         eax,dword ptr [array]
00281A8F  add         eax,dword ptr [ebp-8]
00281A92  mov         cl,byte ptr [eax]
00281A94  add         cl,1
00281A97  mov         edx,dword ptr [array]
00281A9A  add         edx,dword ptr [ebp-8]
00281A9D  mov         byte ptr [edx],cl
        }
00281A9F  jmp         test_body<536870912,2>+2Ah (0281A7Ah)
    }
00281AA1  jmp         test_body<536870912,2>+12h (0281A62h)

A:

TL;DR: Your test is not correct test for cache latency or speed. Instead it measures some problems of chopping complex code through OoO CPU pipeline.
Use right tests for measuring cache and memory latency: lat_mem_rd from lmbench; and right tests for speed (bandwidth) measurements: STREAM benchmark for memory speed; tests from memtest86 for cache speed with rep movsl main operation)
Also, in modern (2010 and newer) desktop/sever  CPUs there is hardware prefetch logic built in near L1 and L2 caches which will detect linear access pattern and preload data from outer caches into inner before you will ask for this data: Intel Optimization Manual - 7.2 Hardware prefetching of data, page 365; intel.com blog, 2009. It is hard to disable all hardware prefetches (SO Q/A 1, SO Q/A 2)
Long story:
I will try to do several measurements of similar test with perf performance monitoring tool in Linux (aka perf_events). The code is based on program from Joky (array of 32-bit ints, not of chars), and was separated into several binaries as: a5 is for size 2^5 = 32; a10 => 2^10 = 1024 (4 KB); a15 => 2^15 = 32768, a20 (1 million of ints = 4 MB) and a25 (32 millions of ints = 128MB). The cpu is i7-2600 quad-core Sandy Bridge 3.4 GHz.
Let's start with basic perf stat with default event set (some lines are skipped). I selected 2^10 (4 KB) and 2^20 (4 MB)
$ perf stat ./a10
Size=1024 ITERATIONS=1048576, TIME=2372.09 ms

 Performance counter stats for './a10':

               276 page-faults               #    0,000 M/sec
     8 238 473 169 cycles                    #    3,499 GHz
     4 936 244 310 stalled-cycles-frontend   #   59,92% frontend cycles idle
       415 849 629 stalled-cycles-backend    #    5,05% backend  cycles idle
    11 832 421 238 instructions              #    1,44  insns per cycle
                                             #    0,42  stalled cycles per insn
     1 078 974 782 branches                  #  458,274 M/sec
         1 080 091 branch-misses             #    0,10% of all branches

$ perf stat ./a20
Size=1048576 ITERATIONS=1024, TIME=2432.4 ms

 Performance counter stats for './a20':

             2 321 page-faults               #    0,001 M/sec
     8 487 656 735 cycles                    #    3,499 GHz
     5 184 295 720 stalled-cycles-frontend   #   61,08% frontend cycles idle
       663 245 253 stalled-cycles-backend    #    7,81% backend  cycles idle
    11 836 712 988 instructions              #    1,39  insns per cycle
                                             #    0,44  stalled cycles per insn
     1 077 257 745 branches                  #  444,104 M/sec
            30 601 branch-misses             #    0,00% of all branches

What we can see here? Instruction counts are very close (because Size*Iterations is constant), cycle count and time are close too. Both examples have 1 billion branches with 99% good prediction. But there is very high 60% stall count for frontend and 5-8% for backend. Frontend stalls are stalls in the instruction fetch and decode, it can be hard to tell why, but for your code frontend can't decode 4 instructions per tick (page B-41 of Intel optimisation manual, section B.3 - "Performance tuning techniques for ... Sandy Bridge", subsection B.3.2 Hierarchical Top-Down Performance Characterization ...)
$ perf record -e stalled-cycles-frontend ./a20
Size=1048576 ITERATIONS=1024, TIME=2477.65 ms
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.097 MB perf.data (~4245 samples) ]
$ perf annotate -d a20|cat
 Percent |      Source code & Disassembly of a20
------------------------------------------------
         :      08048e6f <void test_body<1048576u, 1024u>(int volatile*)>:

   10.43 :       8048e87:       mov    -0x8(%ebp),%eax
    1.10 :       8048e8a:       lea    0x0(,%eax,4),%edx
    0.16 :       8048e91:       mov    0x8(%ebp),%eax
    0.78 :       8048e94:       add    %edx,%eax
    6.87 :       8048e96:       mov    (%eax),%edx
   52.53 :       8048e98:       add    $0x1,%edx
    9.89 :       8048e9b:       mov    %edx,(%eax)
   14.15 :       8048e9d:       addl   $0x1,-0x8(%ebp)
    2.66 :       8048ea1:       mov    -0x8(%ebp),%eax
    1.39 :       8048ea4:       cmp    $0xfffff,%eax

Or here with raw opcodes (objdump -d), some have rather complicated indexing, so possible they can't be handled by 3 simple decoders and waits for the only complex decoder (image is there: http://www.realworldtech.com/sandy-bridge/4/)
 8048e87:       8b 45 f8                mov    -0x8(%ebp),%eax
 8048e8a:       8d 14 85 00 00 00 00    lea    0x0(,%eax,4),%edx
 8048e91:       8b 45 08                mov    0x8(%ebp),%eax
 8048e94:       01 d0                   add    %edx,%eax
 8048e96:       8b 10                   mov    (%eax),%edx
 8048e98:       83 c2 01                add    $0x1,%edx
 8048e9b:       89 10                   mov    %edx,(%eax)
 8048e9d:       83 45 f8 01             addl   $0x1,-0x8(%ebp)
 8048ea1:       8b 45 f8                mov    -0x8(%ebp),%eax
 8048ea4:       3d ff ff 0f 00          cmp    $0xfffff,%eax

Backend stalls are stalls created by waiting for memory or cache (the thing you are interested in when measuring caches) and by internal execution core stalls:
$ perf record -e stalled-cycles-backend ./a20
Size=1048576 ITERATIONS=1024, TIME=2480.09 ms
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.095 MB perf.data (~4149 samples) ]
$ perf annotate -d a20|cat
    4.25 :       8048e96:       mov    (%eax),%edx
   58.68 :       8048e98:       add    $0x1,%edx
    8.86 :       8048e9b:       mov    %edx,(%eax)
    3.94 :       8048e9d:       addl   $0x1,-0x8(%ebp)
    7.66 :       8048ea1:       mov    -0x8(%ebp),%eax
    7.40 :       8048ea4:       cmp    $0xfffff,%eax

Most backend stalls are reported for add 0x1,%edx because it is the consumer of data, loaded from the array in previous command. With store to array they account for 70% of backend stalls, or if we multiply if for total backend stall portion in the program (7%), for the 5% of all stalls. Or in other words, the cache is faster than your program. Now we can answer to your first question:

Why the time taken does not increase at all regardless of the size of my array?

You test is so bad (not optimized), that you are trying to measure caches, but they have only 5% slowdown on total run time. Your test is so unstable (noisy) that you will not see this 5% effect.
With custom perf stat runs we also can measure cache request-to-miss ratio. For 4 KB program L1 data cache serves 99,99% of all loads and 99,999% of all stores. We can note that your incorrect test generate several times more requests to cache than it is needed to walk on array and increment every element (1 billion loads + 1 billion stores). Additional accesses are for working with local variables like x, they always served by cache because their address is constant)
$ perf stat -e 'L1-dcache-loads,L1-dcache-load-misses,L1-dcache-stores,L1-dcache-store-misses' ./a10
Size=1024 ITERATIONS=1048576, TIME=2412.25 ms

 Performance counter stats for './a10':

     5 375 195 765 L1-dcache-loads
           364 140 L1-dcache-load-misses     #    0,01% of all L1-dcache hits
     2 151 408 053 L1-dcache-stores
            13 350 L1-dcache-store-misses

For 4 MB program hit rate is many-many times worse. 100 times more misses! Now 1.2 % of all memory requests are served not by L1 but L2.
$ perf stat -e 'L1-dcache-loads,L1-dcache-load-misses,L1-dcache-stores,L1-dcache-store-misses' ./a20
Size=1048576 ITERATIONS=1024, TIME=2443.92 ms

 Performance counter stats for './a20':

     5 378 035 007 L1-dcache-loads
        67 725 008 L1-dcache-load-misses     #    1,26% of all L1-dcache hits
     2 152 183 588 L1-dcache-stores
        67 266 426 L1-dcache-store-misses

Isn't it a case when we want to notice how cache latency goes from 4 cpu ticks up to 12 (3 times longer), and when this change affects only 1.2% of cache requests, and when our program has only 7% slowdown sensitive to the cache latencies ???
What if we will use bigger data set? Ok, here is a25 (2^25 of 4-byte ints = 128 MB, several times more than cache size):
$ perf stat   ./a25
Size=134217728 ITERATIONS=8, TIME=2437.25 ms

 Performance counter stats for './a25':

           262 417 page-faults               #    0,090 M/sec
    10 214 588 827 cycles                    #    3,499 GHz
     6 272 114 853 stalled-cycles-frontend   #   61,40% frontend cycles idle
     1 098 632 880 stalled-cycles-backend    #   10,76% backend  cycles idle
    13 683 671 982 instructions              #    1,34  insns per cycle
                                             #    0,46  stalled cycles per insn
     1 274 410 549 branches                  #  436,519 M/sec
           315 656 branch-misses             #    0,02% of all branches

$ perf stat -e 'L1-dcache-loads,L1-dcache-load-misses,L1-dcache-stores,L1-dcache-store-misses' ./a25
Size=134217728 ITERATIONS=8, TIME=2444.13 ms

 Performance counter stats for './a25':

     6 138 410 226 L1-dcache-loads
        77 025 747 L1-dcache-load-misses     #    1,25% of all L1-dcache hits
     2 515 141 824 L1-dcache-stores
        76 320 695 L1-dcache-store-misses

Almost the same L1 miss rate, and more backend stalls. I was able to get stats on "cache-references,cache-misses" events ans I suggest they are about L3 cache (there is several times more requests to L2):
$ perf stat -e 'cache-references,cache-misses' ./a25
Size=134217728 ITERATIONS=8, TIME=2440.71 ms

 Performance counter stats for './a25':

        17 053 482 cache-references
        11 829 118 cache-misses              #   69,365 % of all cache refs

So, miss rate is high, but the test does 1 billion of (useful) loads, and only 0.08 billion of them misses L1. 0.01 billion of requests are served by memory. Memory latency is around 230 cpu clocks instead of 4 clock L1 latency. Is the test able to see this? May be, if the noise is low.


Q:

getting a value from a variable in jsp's input type

In my jsp i have a variable
String str = "Get_Name";

What can i do to have my variable(str)  directly accessed in the input type shown below? By this I want to see the form auto filled with the the variable I have instead of me filling it.

<input id="vendorName" name="vendorName" type="text" class="txtsmall2" />

A:

ANSWER ALSO CONTAINS SOLUTION FOR PROBLEM DISCUSSED IN COMMENTS.
Do this.
<%
    long val = 2;   //can be anything.
    if(val > 1) {
%>
<input id="vendorName" name="vendorName" type="text" class="txtsmall2" value="<%=str%>"/>
<%
    else {
%>
<input id="vendorName" name="vendorName" type="text" class="txtsmall2" />
<%
    }
%>

<%=str%> is called as expression tag.


Q:

Sum values in text with PowerShell

I have this ps code
PS > Select-String -path .\build-count-warn.txt -pattern "[1-9]?[0-9]+ warn"

warn.txt:1:    0 Warning(s)
warn.txt:2:    1 Warning(s)
warn.txt:3:    2 Warning(s)

..
So how to extend the ps script and report the sum of 0+1+2=3

A:

Capture the numeric value in the regex like so:
PS> "0 warnings","1 warnings","5 warnings" | Select-String "(\d+) warnings" |
        Foreach {$_.Matches.Groups[1].Value} | Measure -Sum

Count    : 3
Average  :
Sum      : 6
Maximum  :
Minimum  :
Property :

FYI I tested this on PowerShell V3 which supports member enumeration.  On V2, you may need to do this:
PS> "0 warnings","1 warnings","5 warnings" | Select-String "(\d+) warnings" |
        Foreach {$_.Matches | Foreach {$_.Groups[1].Value}} | Measure -Sum


Q:

Using Visual Studio with a screen reader without paying for an expensive edition

I'm a totally blind programmer who would like to learn .net.
It appears that the Visual Studio express editions are not accessible since the scripts that come with Jaws for Windows, the screen reading software I use, requires the VS object model to make Visual Studio accessible. This is not available in the express editions, so the scripts may partially work or not work at all.
None of the options mentioned in this question apply to me and I don't want to spend $500 or more to buy Visual Studio professional when I may never use it for a job.
If I take the time to try out the express versions and run into issues is there any way to contact Microsoft without my questions/feedback being lost in a black hole?

A:

You can get a 90 day free trial of Visual Studio at http://www.microsoft.com/visualstudio/ that should enable you to give it a darn good try. If you like it, and you decide you will go into .NET development, you will probably qualify for BizSpark if you decide to make a product you will sell. I agree that if you only intend to use it while working for a large company, you won't qualify, but then your employer will provide it, right?
Beyond that practical information, some general encouragement and suggestions. There was a 2004 video on Channel 9 about an intern who used a screen reader and Braille keyboard to code. It's at http://channel9.msdn.com/Blogs/TheChannel9Team/Kenneth-Spector-Coding-without-seeing-the-screen and while I realize you may not be able to see it, others who use this question later might. In the comments to that video, Sara Ford identified herself as the "go to" person for accessibility at Microsoft and encouraged people to contact her. Sara has since left Microsoft, but I think it's a good bet there is still such a person. I've had remarkable luck calling the main switchboard and asking for "the person who handles" whatever I want to talk about; you could try doing the same thing. That could lead to a conversation about how well Express works with Jaws.
There is an entire Developer Accessibility area on MSDN http://msdn.microsoft.com/en-us/windows/bb735024.aspx although from a quick read it seems to be more about helping developers to write apps that are accessible. However it has a TON of links including to forums and blogs, so perhaps one of them will be helpful. I think you'll find Microsoft will be delighted to help you succeed at this endeavour.

A:

Visual Studio community edition appears to provide access to the VS object model. I was able to create a project and do basic code editing with no issues. I've just started but it looks like this solves my issue.


Q:

Read and Write Card Details using a Smart Card Reader

I need to integrate my application with a Smart Card Reader. Its a ContactLess Card Reader, Model No. ACR122U-A2 by Advanced Card Systems (www.acs.com.hk).
Currently my customer is already using another application developed by someone else, which uses this Card Reader. They usually place the Card on top of the Card Reader, even though its a ContactLess Card Reader.
This Card is used in a Club for member access. I need to read Member ID No. Name, etc. and also write the code to activate the Card.
I need sample C# code. I have gone through the technical manual on the manufacturer's site, but it provides too many low level details using Hexadecimal Codes. I am looking for a high level example using C#.
EDIT 1:
Since the data in the card is written by another application, whether I will be able to read the data meaningfully without knowing the schema details? I am sorry if this is a silly question, but I am programming the smart card for the 1st time.

A:

There is an SDK for this product which indicates that it contains sample code in C#.
http://www.acs.com.hk/index.php?pid=product&id=ACR122-SDK
I think this is the best place to start.  Hope that helps.


Q:

Access Wifi From Dock on a House Boat

My dad has a houseboat on a lake.  The dock that he is at offers free WiFi for the house boat users.  However, the antenna is about 150-200 feet away and he is unable to get a signal strong enough to connect to.
He would like to be able to extend the WiFi network so that him and his guests can easily connect to the WiFi network from anywhere on his boat.  What does he need to purchase to be able to do this?  He is not allowed to modify any of the dock's equipment so the solution has to be equipment that he can install on his boat.
Thanks!

A:

You need to install a wireless router in the boat.  That'll give you coverage of the boat.  The next issue is how to connect WAN input on the router to the wireless signal coming from the dock.  While there are a lot of ways to do that, I find Ubiquity equipment to be pretty excellent.  You might just get a Bullet M - Titanium, maybe, 'cause he's out there on the water - and a mast antenna.  You don't want anything too focused for the antenna, given that you're on a boat and there will at least be drift, if not outright rocking.  So stay away from the parabolic dishes or the yagis.  Probably just a mast/"omni" antenna would do, and at that distance 12dBi would probably be sufficient.
Ubiquity at Streakwave, for example.  Look for Bullet M in the products list.  M2 is for 2.4GHZ band, M5 for the 5GHZ band.  HP means it puts out a higher power level, which you may or may not need.
Omni antennas at Streakwave
The Bullet will screw on to the base of the antenna (make sure they are both N-type connectors and the proper Male/Female relationship).  That will be set into "base-station" mode.  The Bullet will then connect to the router using regular cat-5e cable.  Get some external cable so it's waterproof.
I do the same thing connecting to a university wireless from my roof, though I use a Ubiquity Nanobridge which comes with an 18dBi dish.
Do notice that I've used "probably" and the like.  Wireless is a bit of an art form.  You may have to play.
That's it!  Have fun.


Q:

Does UPDATE happen column by column in SQL Server

I have following query -
 UPDATE THINGS

SET Col 1 = CASE when 'A' then 'APPLE'
                 when 'B' then 'BALL'
                 when 'C' then 'CARROT'
                 else NULL
                 end,
    Col 2 = Case Col 1 when 'APPLE' then 'FRUIT'
                       when 'BALL'  then 'TOY'
                       when 'CARROT' then 'SALAD'
             else NULL
             end

My question is will the update happen on column by column basis so that I can get updated values in my Col 2 successfully? If it is not possible by above query, is there any other way to update it within a single query? I cannot write two separate queries.

A:

You can use this approach by using variable to store data and then use it foe next column.
DECLARE @val VARCHAR(20) -- type of Col1
UPDATE THINGS
SET @val = [Col 1] = CASE WHEN 'A' THEN 'APPLE'
                          WHEN 'B' THEN 'BALL'
                          WHEN 'C' THEN 'CARROT'
                     END,
       [Col 2] = CASE @val WHEN 'APPLE'  THEN 'FRUIT'
                           WHEN 'BALL'   THEN 'TOY'
                           WHEN 'CARROT' THEN 'SALAD'
                 END


Q:

How far are we from maturing to a full site?

We've been in beta for pretty long, how far are we from maturing into a full site? How do we move towards it? And who is the governing authority that determines if a site should progress or not?

A:

The StackExchange community team decides when to promote or shut down a beta.
Robert Cartaino has written about the graduation requirements a few times, but the basic gist is that  it's mostly subjective.  The only hard requirements I've seen repeatedly mentioned are the duration (over 90 days) and the number of closers and editors, all of which we technically meet.
However, looking at some of the other sites in beta, I would suspect the SE team is still waiting to see if the traffic and activity on this site will pick up more before they graduate us.  Sites like the Personal Finance beta are in a much healthier state, yet also haven't been graduated (though I think they are close).

A:

I think this overview might give you some idea of why the SE team hasn't graduated the site yet:
http://area51.stackexchange.com/proposals/7526/japanese-language-usage


Q:

SQL query to calculate coordinate proximity

I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format:
6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% )))

Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc.
I'm writing this mostly as a note for myself, but improvements are always welcome. :)
Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an appropriate alternative number to use meters, miles etc.

A:

For databases that don't support trig (such as SQLite) you can use pythagorus. Even if your database does support trig, pythagorus is much faster. The caveats are:

you need to store coords in x,y grid instead of (or as well as) lat,lng;
the calculation assumes 'flat earth', but this is fine for relatively local searches.

Here's an example from a Rails project I'm working on (the important bit is the SQL in the middle):
class User < ActiveRecord::Base
  ...
  # has integer x & y coordinates
  ...

  # Returns array of {:user => <User>, :distance => <distance>}, sorted by distance (in metres).
  # Distance is rounded to nearest integer.
  # point is a Geo::LatLng.
  # radius is in metres.
  # limit specifies the maximum number of records to return (default 100).
  def self.find_within_radius(point, radius, limit = 100)

    sql = <<-SQL
      select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d
      from users where #{(radius ** 2)} >= d
      order by d limit #{limit}
    SQL

    users = User.find_by_sql(sql)
    users.each {|user| user.d = Math.sqrt(user.d.to_f).round}
    return users
  end


Q:

Get page referer and missing page that generates Error 404 using PHP

I've been researching online for a way to retrieve the URL that generates a 404 error. I've found various postings on this subject in this and other sites and tried them all. Unfortunately I'm still not being able to get what I want. I will try to explain what I've done and what I'm getting.
SCENARIO:
I have a page. Let's call http://www.example.com/index.php.
In this page, I have a link, to let's say wrong_page.php or, if you prefer, http://www.example.com/index.php.
As the page wrong_page.php doesn't really exists, When someone click on this link, it redirects to error404.php. (to make it easier, all pages are in the root directory.
Question: Is it possible for error404.php to give me both index.php as the original page where the wrong link resides and wrong_page.php as the wrong link itself?
SETUP
At the root folder of my site I have  .htaccess file with the following directive:
ErrorDocument 404 error404.php

Inside error404.php I loop through the whole $_SERVER variable and, this is what I get:

If the visitor clicks on the wrong_link (the one that leads to wrong_page.php),
I get $_SERVER['HTTP_REFERER'] = 'index.php' but no reference to wrong_page.php;
If the visitor types wrong_page.php in the address bar, $_SERVER['HTTP_REFERER'] doesn't even exist (tested with isset() function).

Moreover, in both cases $_SERVER['REQUEST_URI'] = 'error404.php'
I tried all $SERVER global variables starting with "REDIRECT" as mentioned in other postings, but they do not existed (also tested with isset() function).
Also, I tried this in two different servers: my own instance of WAMP (that I use for development) and a production server running apache.
In my computer, when I look at server error logs (apache_error.log), I find a line like this:
[Wed Jul 23 11:28:51 2014] [error] [client 127.0.0.1] File does not exist: /www.example.com  referer: /www.example.com/index.php

In the production server, this same line does not get created when I reproduce the same error.
What am I missing? Or is it all that I can get?
Are there any server parameters I can change to get what I want?
Is there another global variable I should look at?
As I said, I know there are many other postings regarding this, but they all talk about these same global variables and, as I said, they don't give me what I want (wrong_page.php as the culprit).

A:

I finally found the "solution" if I can call it a solution.
The whole problem was in the URL used in the directive inside .htaccess.
I wrote my directive as being:
ErrorDocument 404 error404.php

But inside my actual .htaccess I had the directive as
ErrorDocument 404 http://www.example.com/error404.php

The presence of http://www.example.com was the problem. All I had to do was make the directive as follow:
ErrorDocument 404 /error404.php

This way, $_SERVER['REQUEST_URI'] gives me the wrong URI requested by the user. If it is a link in my site, it will give me the page where the link exists in $_SERVER['HTTP_REFERER']. Otherwise, if the user simply typed the wrong URI in the address bar, $_SERVER['HTTP_REFERER'] will be blank.
I hope this helps others with the same issue.


Q:

R not being able to find the file despite being in correct directory

I have question regarding a project I have to do about a health student study. I cannot import the csv file via read.csv or read.csv2 despite having transformed all files to csv and being in the correct folder.
Here are the command lines:
setwd ("C:/Users/fek/Desktop/Analyse i-Share")
getwd()
TA<-read.csv2(file=Biobanque.csv, header=TRUE, sep=",", dec=",", fill=TRUE)

And here are the results in the console window:
setwd ("C:/Users/fek/Desktop/Analyse i-Share")

getwd()

[1] "C:/Users/fek/Desktop/Analyse i-Share"
TA<-read.csv2(file=Biobanque.csv, header=TRUE, sep=",", dec=",", fill=TRUE)

[1] Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
objet 'Biobanque.csv' introuvable
To translate from french, it says it can't find the file!

A:

The problem is just what it says.  By omitting the quotes around "Biobanque.csv", R thinks you are talking about an object whose name is Biobanque.csv. And R is confused because of course you have not created an object by that name.


Q:

What is an example of a Monte-Carlo algorithm for finding a Hamiltonian path?

I've recently been made aware that there exist Monte-Carlo algorithm(s?) for determining whether a Hamiltonian path exists in a graph. I am struggling to figure out how it would work. What is the random element?

A:

There are several such algorithms for various graph problems; for Hamiltonian path one example is due to Björklund [1]. These algorithms are often algebraic and the "random element" stems from the application of the Schwartz–Zippel lemma. Usually, the algorithms work so that the graph property we are interested in is somehow represented as a (multivariate) polynomial with the property that that a solution exists precisely when the polynomial is not identically zero.

[1] Björklund, Andreas. "Determinant sums for undirected hamiltonicity." SIAM Journal on Computing 43.1 (2014): 280-299.


Q:

Understanding JAVA generic keyword 'super'

Recently some people said that I was wrong when I explained why one cannot insert a Number object into a list declared as List<? super RationalNumber>.
(This assumes that RationalNumber is a subclass of Number)
My explanation was that in List<? super RationalNumber> the <? super RationalNumber> stands for an unknown super class of RationalNumber. This means that <? super RationalNumber> indicates that a valid object for List<? super RationalNumber> is an object that extends an unknown super class of RationalNumber.
Since an unknown super class of RationalNumber is really unknown (e.g. it can be an interface X instead of Number), there is not guarantee that Number is a sub-class of X i.e. implements X, so Number is not a valid substitution of <? super RationalNumber>.
What is wrong with this explanation?
Edit: Note that I am asking for what wrong with the way I explain, my explanation. Not another explanation for the original question.
Thanks.

A:

List<? super RationalNumber> is a list of some type X that is a superclass of RationalNumber.  Your assumption is that RationalNumber is a subclass of Number, so the possible candidates for X are RationalNumber, Number, or Object.  The most restrictive possibility is that X is RationalNumber itself.  A List<RationalNumber> can contain only instances of RationalNumber, and cannot contain instances of Number.
In short, a List<? super T> is a list that can accept instances of T, but the current contents are of unknown type.  This contrasts with List<? extends T>, which contains instances of T, but does not allow adding new elements because the type accepted is unknown.
This example illustrates the use of super:
void storePies(List<? super RationalNumber> list) {
    list.add(new RationalNumber(22, 7))
    list.add(new RationalNumber(355, 113))
}

...
List<Number> list = new ArrayList<Number>();
storePies(list);
list.add(3.14159265358979);

This example illustrates the use of extends:
double sum(Collection<? extends Number> numbers) {
    double s = 0;
    for (Number n: numbers) { s += n.doubleValue(); }
    return s;
}

List<Integer> somePrimes = new ArrayList<Integer>();
somePrimes.add(5);
somePrimes.add(17);
double total = sum(somePrimes);

A:

See also:

Lower-bounded wildcards
the answers to the question java generics super keyword on Stackoverflow.

A digression. Feel free to skip.
For programmers who are also familiar with C#, a similar feature exists:

Covariance and Contravariance in Generics

The terms, covariance and contravariance, can be traced back to the early discussions coming from the Liskov substitution principle (LSP).

The design goal of lower-bounded wildcard (LBWC) is to ensure the type safety of the following piece of code.
(This is just one example; one of the very simple example among others.)
List<? super RationalNumber> containerOne = new ArrayList<RationalNumber>();
List<? super RationalNumber> containerTwo = new ArrayList<Number>();
List<? super RationalNumber> containerThree = new ArrayList<Object>();

RationalNumber itemValue = new RationalNumber(22, 7);

containerOne.add(itemValue);
containerTwo.add(itemValue);
containerThree.add(itemValue);

In short, LBWC allows the "handles" - generic classes having an LBWC (containerOne, containerTwo, containerThree in the above sample) to:

Be assigned instances of the generic class (of type parameter T) whenever it is known that RationalNumber can be safely up-cast to T.

Now, we use this knowledge and try to answer the question: can we pass in a Number to such a "handle" - a generic class having an LBWC of RationalNumber?

Given that

It is valid to assign an instance of new List<RationalNumber>() to a handle of List<? super RationalNumber> varGeneric.
Of course it is valid to do something entirely different; but the design of LBWC is that this is the situation that it needs to deal with.

We obtain this corollary question:

Can we call new List<RationalNumber>().add(new Number(...)) ?

Of course not.

Seeing that it is LBWC's design goal to prevent this from happening, one can derive this conclusion:

If LBWC is designed to be enforceable at all (by the compiler, or language police), it must prevent this assignment (passing in a Number for a type ? for which the LBWC is RationalNumber) from happening.

This answers the question from a design perspective. The matter of enforcement can only be answered by senior members of the community who are familiar with the construction of the Java language and its compiler tools. Comments from the general crowd will only provide speculations, or "hypotheses" or "theories".


Q:

Is it possible to use spread on multiple columns in tidyr similar to dcast?

I have the following dummy data:
library(dplyr)
library(tidyr)
library(reshape2)
dt <- expand.grid(Year = 1990:2014, Product=LETTERS[1:8], Country = paste0(LETTERS, "I")) %>%   select(Product, Country, Year)
dt$value <- rnorm(nrow(dt))

I pick two product-country combinations
sdt <- dt %>% filter((Product == "A" & Country == "AI") | (Product == "B" & Country =="EI"))

and I want to see the values side by side for each combination. I can do this with dcast:
sdt %>% dcast(Year ~ Product + Country)

Is it possible to do this with spread from the package tidyr?

A:

One option would be to create a new 'Prod_Count' by joining the 'Product' and 'Country' columns by paste, remove those columns with the select and reshape from 'long' to 'wide' using spread from tidyr.
 library(dplyr)
 library(tidyr)
 sdt %>%
 mutate(Prod_Count=paste(Product, Country, sep="_")) %>%
 select(-Product, -Country)%>%
 spread(Prod_Count, value)%>%
 head(2)
 #  Year      A_AI       B_EI
 #1 1990 0.7878674  0.2486044
 #2 1991 0.2343285 -1.1694878

Or we can avoid a couple of steps by using unite from tidyr (from @beetroot's comment) and reshape as before.
 sdt%>%
 unite(Prod_Count, Product,Country) %>%
 spread(Prod_Count, value)%>%
 head(2)
 #   Year      A_AI       B_EI
 # 1 1990 0.7878674  0.2486044
 # 2 1991 0.2343285 -1.1694878

A:

With the new function pivot_wider() introduced in tidyr version 1.0.0, this can be accomplished with one function call.
pivot_wider() (counterpart: pivot_longer()) works similar to spread().
However, it offers additional functionality such as using multiple key/name columns (and/or multiple value columns).
To this end, the argument names_from—that indicates from which column(s) the names of the new variables are taken—may take more than one column name (here Product and Country).
library("tidyr")

sdt %>%
    pivot_wider(id_cols = Year,
                names_from = c(Product, Country)) %>%
    head(2)
#> # A tibble: 2 x 3
#>     Year   A_AI    B_EI
#>    <int>  <dbl>   <dbl>
#>  1  1990 -2.08  -0.113
#>  2  1991 -1.02  -0.0546

See also: https://tidyr.tidyverse.org/articles/pivot.html


Q:

Add class to  if there are more than 2  nested

I Have something like this:

1

2

3

4

And I need to add a class to the ul element if there are more than 3 items nested.

A:

First, you have to can get you desired ul > li, then you can easily check length and apply class

var liList = document.getElementById("mylist").getElementsByTagName("li");
if (liList.length > 3) {
    document.getElementById("mylist").className += " customlist";
}
.customlist {
  color: red;
}

1

2

3

4


Q:

Diet balance between family and health

I live with my family who eat a regular western diet (or maybe slightly healthier becuase of me). They eat few and eat mostly storebought. They are not interested in being healthy.
That's fine becuase they don't care and I can't do anything about it (I tried). However I want to be different. We always eat dinner together, and they don't exactly make kale salads. Tonight is salmon noodles with 'things' like refined wheat noodles, soy sauce, fish farm salmon, honey, etc. If there's anything I'm trying to avoid, it will crop up in significant amounts from once a week to every night. They go out for dinner/lunch almost once a week, and it isn't nice to order salads at restuarant when everyone else indulges.
They say they can't order takeaway for dinner, or make 'fun stuff' more often because of me. Where can I draw the line between healthy and social? If they go out for ice-cream, I won't go.
I don't have any conditions and have been 'different' for about a year (lots of nutritious food, little junk).

A:

(Note: I'm well aware this question will probably be closed because it's not related to exercise and is primarily opinion based, but I'll try and help anyway)
First off, well done on deciding to clean up your diet!
Unfortunately, there's no easy solution to this, it just comes down to compromise. You say you've tried changing their diets and they don't care about it, I'd be interested to know how you tried. I've always found that gentle nudges are much more effective than large pushes, and playing the long game can usually be successful.
By that, I mean that instead of standing in front of your family and yelling "You all eat rubbish and it's killing you!", try making small changes that they won't necessarily notice. Change the soy sauce for a low salt variety and see if they notice the difference, try rice noodles instead of the refined wheat variety (it's an arguable difference), add in some veg to the noodles to up the nutrient value a bit.
All of this does necessitate you being able to have an input in the cooking process, either by helping make the food, or by being able to request small changes to the meal.
As for the ordering a salad when dining out, there are other options besides salad, such as changing chips for vegetables, ordering a side of seasonal veg instead of the burger bun, etc, etc. They're simple substitutions that most restaurants are happy to make for you. (I actually don't see the issue ordering a salad when the person opposite me is dining on a burger and chips, but then I'm used to getting odd looks for my food choices).
If they're complaining about not being able to order takeaway or make "fun stuff" because of your food choices, then I'd suggest either cooking something for yourself on the evenings they want to order takeaway, or learn to cook and show them that healthy doesn't have to be boring!
Lastly, since this is more of an ongoing question than a simple Q&A style one, which is what StackExchange is primarily for, I'd suggest trying to post the same question on a forum such as https://www.reddit.com/r/Fitness/. People there are generally good at offering advice about how to get around problems such as yours.
Good luck!


Q:

Determining sunrise and sunset times based on azimuth and elevation

If I observe the sun and measure the local azimuth and elevation, and I also have my latitude, can I calculate the local sunrise and local sunset times? If so, how would I calculate it?
Further, can the same calculations be used for the moonrise and moonset?

A:

$
\cos ^{-1}\left(-\frac{\tan (\lambda ) (\cos (\lambda ) \cos (\phi ) \cos
(Z)+\sin (\lambda ) \sin (Z))}{\sqrt{(\cos (\lambda ) \sin (Z)-\sin (\lambda)
\cos (\phi ) \cos (Z))^2+\sin ^2(\phi ) \cos ^2(Z)}}\right)-\tan^{-1}
(\cos (\lambda ) \sin (Z)-\sin (\lambda ) \cos (\phi ) \cos (Z),\sin
(\phi ) (-\cos (Z)))
$
is the amount of time from now (see important notes below) a celestial object will set, where:

$\phi$ is the azimuth of the object
$Z$ is the altitude of the object above the horizon
$\lambda$ is the latitude of the observer

Note the two-argument form of arctangent is required for accuracy: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Two-argument_variant_of_arctangent
Important notes (MUST READ!):

The result is in radians. To convert to sidereal hours, multiple by $\frac{12}{\pi }$
If the object has a fixed right ascension and declination, divide sidereal hours by 1.002737909350795 to get clock hours.
For the Sun (which doesn't have fixed right ascension/declination), do NOT divide as above. By not dividing, you compensate for the Sun's change in right ascension.
For the Moon, see "The Moon" section below.
The time computed above is for geometric midpoint setting. In reality, refraction near the horizon means the object will set later. Additionally, for objects that have an angular diameter (eg, the Sun), setting usually means when the top edge disappears over the horizon, which will make the set time even later. Accounting for both effects should be possible, but might require numerical methods instead of a closed form formula as above.
If the quantity inside the arccosine is greater than 1, the object is always in the sky and never sets or rises.
If the quantity inside the arccosine is less than -1, the object is never in the sky and thus also never sets or rises.
I did only minimal testing. As always, do not rely on my answers for anything important.

The Moon:

The Moon's right ascension and declination change rapidly, so this calculation does not work well for the moon.
You could compensate for the change in right ascension (and thus hour angle) by approximating the increase as 24 hours every 27.32158 days (its sidereal period) and do an iterative calculation.
An even better compensation for the change in right ascension would be to approximate the moon's movement in ecliptic longitude (which is more constant than its movement its right ascension) as 360 degrees per 27.32158 days and then project the ecliptic longitude back to right ascension, and then iterate.
Compensating for the moon's change in declination is more difficult. The moon's ecliptic latitude (which can be converted to declination) varies sinusoidally, but the equation $\sin (x)=a$ normally has two solutions. Unless you know whether the moon's ecliptic latitude is increasing or decreasing (ie, whether it's between ascending and descending nodes or vice versa), you won't know the direction of declination change.

Less important notes (optional):

See Need Simple equation for Rise, Transit, and Set time for more general equations on when an object rises/sets/etc.
Calculations for this answer at: https://github.com/barrycarter/bcapps/blob/master/STACK/bc-object-riset-from-az-elt.m
Related calculations: https://github.com/barrycarter/bcapps/blob/master/STACK/bc-rst.m
Mathematica was unable to find a simpler form for the "time to set" above, though I sense a simpler form does exist (I could be wrong).
If you know the Sun's declination (which you can get from its azimuth and elevation as above), you can almost determine the date. However, the sun reaches a given declination twice a year (example: it reaches 0 degrees declination on both equinoxes, by definition), so you can only know it's one of two days.

Solution notes:
I learned quite a bit answering this question, and thought it was only solvable numerically until I figured out the shortcut:

To convert from the azimuth/elevation sphere to the hour angle/declination sphere, you just rotate around the y axis by $\frac{\pi }{2}-\lambda$ (90 degrees minus the latitude) and then rotate $pi$ (180 degrees) around the z axis.
Once you have the declination, computing the hour angle when an object sets is easy.
You then subtract the setting time from the current hour angle to get the answer.

TODO: I was hoping to add some graphs/visualizations to this answer but couldn't quite get things working.


Q:

Passing values from javascript to controller

I am setting a value of hidden field in javascript which is fired on button click but when controller function is called hidden field value is not passed along as I expected.
Visual Force Page:

<apex:form id="upload-form">
    <apex:pageMessages />

    <apex:outputPanel rendered="{!accountID != ''}">
        <input id="hdnDocName" value="{!filename}" type="hidden" />
        Please select image:
        <input id="idFileUpload" data-max-size="2097152" type="file" name="uploadfile" value="{!doc.body}" accept="image/x-png, image/gif, image/jpeg, image/jpg" />

        <apex:commandButton value="Upload" onClick="if (getName() === false) { return false; }" action="{!SaveAttachment}"/>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!accountID == ''}">
        No valid account selected
    </apex:outputPanel>
</apex:form>

Controller:
public String filename { get; set; }
public Pagereference SaveAttachment()
{
    System.Debug(filename);
    return null;
}

debug statement returns null. How do I pass values?

A:

You are binding the filename field into the page when it is generated but you are not taking advantage of Visualforce's automatic binding of values back into the controller. To do so in this case you will need to use apex:inputHidden:
<apex:inputHidden id="hdnDocName" value="{!filename}"/>

As the id value gets prefixed in the generated HTML you can use jQuery's ends with selector syntax to match the element:
$("[id$='hdnDocName']").val(fileName);


Q:

Need help in clarifying what I'm asking for

How to design a GMPC that will not push the story ahead?
Has been closed as beeing off topic, given the reason that actually I recived many answers on something I wasn't looking for, so beeing unclear.
This has been clarryfied by Erik with his comment on one of my comments on one of the answers where I was complaining of he just tells me aspects but not how to achieve them. He commented:
"right, I understand. I think the question is misunderstood then. You're getting answers for GMPCs who WILL NOT drive the story forward, but it seems you are looking for a GMPC who CANNOT drive the story forward, even when directly asked to do so? – Erik Feb 17 at 11:17"
Which was pretty much on the point.
But I actually have no clue how to make it more clear, since from my point of view it is totally clear.
Since first of all in the title I'm asking for a character design that is supposed to not do. My intention here was metaplaying not beeing supposed, I was assuming this is clear, since I'm asking about a design and not how to play it that way. Is the title the problem and not clear enough?
The introducing backgroundstory why I'm asking this I told to avoid 2 things:
1st to make sure why I decided to handle it fits best this way for my given situation. So desputing answers that would recommend me avoid my problem by another gaming styl to avoid the GMPC.
2nd to make clear again its me who will have trouble in rollplaying it competent not having informations I as player actually have, while the character is trying to get the informations. So that every one understands I'm not looking for a design that makes the character independent from getting the information when rollplayed well, but I'm looking for a design that just makes an character willing to not share the informations even IF he would know about it, so it is working around my lack of rollplaying experience, and makes me stay in character by just saying "I won't tell you" without even exposing this is relevant information.
And finally the TL&DR part was set, so everyone who might have missunderstood my intention of the introduction(You know, I'm used to be missunderstood, so I'm planing allready what one might missunderstand and how I could avoid it eventually), just sees as standalone the question.
"How to design a character in a way, that his trait, behavior or background when roleplayed correctly lets him not participate in decision-making(footnote:Should the character be forced by another PC into making a decision, it is acceptable, since it is an exceptional case not caused by the GMPC's player himself.), while it still is obvious that his motivations are a success of the "party"?"
Here I'm finally off. I don't even have a clue why this was missunderstood.
I said the thing I'm asking for lets the character not participate1 and was even noting that the exceptional case of a situation where the character at least for given circumstances is able to participate, is aceptable. (AFAIK this would expresses that my given post by itself should express that this exception isn't even acceptable without the note).
So what exactly is in my OP flawed that I was by a handfull of people missunderstood? And how to fix it, so the post becomes on-topic?

1actually my impression is this was instead understood as only lets the character passively participate but again, no clue what makes the sentence sound like that?

A:

There are a number of reasons that your question was too broad -- these were addressed in the comments.  Another point is that any answer could be mostly  opinion, based on the question as originally written.
On the bright side, you did provide your up front statement that you were using a GMPC and referred to a question about options for your situation.  That should have ruled out any answer of "don't use a GMPC" since you specifically stated that you had this as your plan, and that it was the core of your problem.  I tried to re emphasize that in the edit to your question.
On the less clear side, it did not to me look as though you folded in Erik's comment.  After your edits and revisions, that point Erik made still wasn't clear in the text of your question, nor in the title.  I tried to address that in the edit as well.

"right, I understand. I think the question is misunderstood then.
  You're getting answers for GMPCs who WILL NOT drive the story forward,
  but it seems you are looking for a GMPC who CANNOT drive the story
  forward, even when directly asked to do so? – Erik Feb 17 at 11:17"

Part of what makes your question difficult is writing style: you use a lot of words to get to a point.  Don't feel bad, I have the same tendency. :-)
The other problems were organizational.  Some of your ideas needed to be rearranged to flow better from point to point.  I tried to assist you with that in the edit.
You didn't identify the class of the PC, nor the GMPC.  Given the variety of combinations between the chosen PC class and your chosen GMPC class, getting a concise and good reply that meets your needs (and isn't mostly opinion) is hard to do without that detail -- nobody knows what class is supporting the PC's class, and thus is less likely to come up with a background and motivation to help answer your specific problem.
As you saw, the answers were varied and some were not all that useful to you(albeit they attracted votes).
A few things that might have helped clear up where your difficulty was coming from:

You have the Starter Set, but do you have the Players Handbook(PHB),
and are you familiar with the variety of backgrounds?  If not, that
would be a good point to explain.
Do you have the Dungeon Masters Guide(DMG), which has the section on
how to customize a background for a character?
You did mention that you do have the Monster Manual.